views:

88

answers:

2
+1  Q: 

PHP - failed write

I am stuck and in need of a hand. Hope someone can help?

Anyone have any idea why I am getting "failed write" in this code?

$write_file = "/usr/home/public_html/php/users_v2.sql";
$write_handle = fopen($write_file, "w") || die("Couln't open users_v2!");

if (is_writeable($write_file)) {
    if ($write_handle === FALSE) echo 'Failed handle?!';
    if (fwrite($write_handle, "Hi\n") === FALSE) echo "Failed write!\n";
}

fclose($write_handle);

Thanks in advance.

A: 

I have seen it used everywhere but the problem is the || die("Couln't open users_v2!");

First I added:

error_reporting(E_ALL);

to see what php is reporting for errors.

$write_handle = fopen($write_file, "w") || die("Couln't open users_v2!");
fclose($write_handle);

Returns an invalid stream handle error and file handle of 1. Without it the returned file handle is "Resource id #x".

Changing the line to:

$write_handle = fopen($write_file, "w"); // || die("Couln't open users_v2!");

and your code works fine. Gonna go post this on php.net now.

Ken
Its running on FreeBSD.
frio80
+1  A: 

By using the OR operator when creating your file handle, you are returning a boolean value depending on the operation. So $write_handle will contain true or false, instead of the file resource. A better way to open a file for writing and test that it was successful would be this:

$write_handle = fopen($write_file, 'w');
if ($write_handle === false)
{
    die('Could not open file ' . $write_file);
}

Additionally, you could use the file_put_contents() function which handles the fopen(), fwrite() and fclose() for you. I only recommend this if you are executing only one write to the same file, as it will be a lot of overhead, and unless you pass the FILE_APPEND flag, it will empty the file for every write.

Jamal Fanaian