laravel file_put_contents 不返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21842479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
file_put_contents does not return a value
提问by Crystal
I'm having trouble using file_put_contents. I thought I could do something like this in laravel/php.
我在使用 file_put_contents 时遇到问题。我以为我可以在 laravel/php 中做这样的事情。
$response = new stdClass();
$key = generateKey(); // generates a 32 bit key
$dir = "/mnt/my-usb";
if (file_put_contents($dir . "/" . "key", $key) === true) {
$response->status = "Fail";
$response->message = "Some user facing message that describes the error";
return Response::json($response, 500);
}
So I thought I could check the status code file_put_contents and return a good error message. However, when I step through this code, once it gets to the if statement, if there is a failure, it never enters the if statement. I'm not sure why. I've tried it withouth the === true and I get the same results. I thought that file_put_contents would return some sort of error code that I could look up and create a user facing message, but it just returns automatically and I cannot create a response to send back to the client. Any thoughts? Thanks in advance.
所以我想我可以检查状态代码 file_put_contents 并返回一个好的错误消息。但是,当我单步执行这段代码时,一旦它进入 if 语句,如果出现故障,它就永远不会进入 if 语句。我不知道为什么。我在没有 === true 的情况下尝试过,我得到了相同的结果。我认为 file_put_contents 会返回某种错误代码,我可以查找并创建面向用户的消息,但它只是自动返回,我无法创建响应以发送回客户端。有什么想法吗?提前致谢。
回答by Samuel Cook
Check the manual: http://php.net/function.file-put-contents
查看手册:http: //php.net/function.file-put-contents
This function returns the number of bytes that were written to the file, or FALSE on failure.
此函数返回写入文件的字节数,失败时返回 FALSE。
Meaning:file_put_contents
will never return TRUE
. It will return false
however, so if you were insistent on using a boolean value then you would need to use:
含义:file_put_contents
永远不会返回TRUE
。false
但是它会返回,所以如果你坚持使用布尔值,那么你需要使用:
if (file_put_contents($dir . "/" . "key", $key) !== false) {
// reset of code
}
Additionally, there are multiple examples on how to make file_put_contents
"die silently" (ie testing that the file can be opened if it exists, checking that the folder is writable, etc.)
此外,还有多个关于如何使file_put_contents
“静默死亡”的示例(即测试文件是否存在可以打开,检查文件夹是否可写等)
回答by Mohamad Hamouday
Try to add full path to your file path , like this :
尝试将完整路径添加到您的文件路径,如下所示:
/home/Site_Name/public_html/