file_put_contents不返回值 [英] file_put_contents does not return a value

查看:249
本文介绍了file_put_contents不返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用file_put_contents时遇到问题.我以为我可以在laravel/php中做这样的事情.

I'm having trouble using file_put_contents. I thought I could do something like this in 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);
}

所以我想我可以检查状态码file_put_contents并返回一个好的错误消息.但是,当我单步执行此代码时,一旦到达if语句(如果失败),它将永远不会输入if语句.我不知道为什么.我已经尝试过=== true,并且得到了相同的结果.我以为file_put_contents将返回某种错误代码,我可以查询该错误代码并创建面向用户的消息,但是它只会自动返回,并且我无法创建响应以发送回客户端.有什么想法吗?提前致谢.

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.

推荐答案

检查手册: http: //php.net/function.file-put-contents

此函数返回写入文件的字节数,如果失败,则返回FALSE.

This function returns the number of bytes that were written to the file, or FALSE on failure.

含义: file_put_contents永远不会返回TRUE.但是它将返回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:

if (file_put_contents($dir . "/" . "key", $key) !== false) {
    // reset of code
}

此外,还有多个示例说明如何使file_put_contents无声死"(即测试文件是否可以打开,是否存在可写文件夹,等等)

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不返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆