1

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.

3
  • Not sure, but can you check if the program has necessary permissions to write to the file? Commented Jul 4, 2009 at 16:23
  • Yeah, I checked that. 777's across the board. Its so weird. Commented Jul 4, 2009 at 16:26
  • Have you checked your server's error logs? Commented Jul 4, 2009 at 17:07

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.