views:

65

answers:

4

I am trying to write to a file. I do a file_exists check on it before I do fopen and it returns true (the file does exist).

However, the file fails this code and gives me the error every time:

$handle = fopen($filename, 'w');
if($handle)
{
    flock($handle, LOCK_EX);
    fwrite($handle, $contents);
}
else
{
    echo 'ERROR: Unable to open the file for writing.',PHP_EOL;
    exit();
}
flock($handle, LOCK_UN);
fclose($handle);

Is there a way I can get more specific error details as to why this file does not let me open it for writing? I know that the filename is legit, but for some reason it just wont let me write to it. I do have write permissions, I was able to write and write over another file.

+1  A: 

If you're using php 5.2+ you might be interested in error_get_last().
On your development system you can also increase the error reporting level, either within the script via error_reporting() or (preferably) in your php.ini.

error_reporting(E_ALL);
ini_set('display_errors', 1);

$handle = fopen($filename, 'w');
if(!$handle) {
  echo 'ERROR: Unable to open the file for writing.',PHP_EOL;
  var_dump(error_get_last());
  exit();
}

flock($handle, LOCK_EX);
fwrite($handle, $contents);
flock($handle, LOCK_UN);
fclose($handle);
VolkerK
I would suggest to use `E_ALL | E_STRICT` (or `-1`? not sure) as error reporting level.
binaryLV
+1  A: 

or general way of getting errors:

ini_set('display_errors',1); // for the development PC only
error_reporting(E_ALL); // ALWAYS

to see the actual error message

Col. Shrapnel
or even more generic way: `ini_set('display-errors', $_SERVER['REMOTE_ADDR'] === '127.0.0.1');` (always), where 127.0.0.1 is developer's IP ;)
binaryLV
A: 

Sounds like the directory you're writing to doesn't have the correct permissions.

Ben Rowe
+2  A: 

Just because the file exists doesn't mean that you have permission to write to it. Before trying to write to a file, you should check to see if PHP has permission to do so using is_writable.

Justin Johnson