file_put_contents does not return a value

laravel, php

Solution

Check the manual: http://php.net/function.file-put-contents

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

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
}

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.)

Problem

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); } ``` 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.

Original source