phpfopen

PHP: failed to open stream: File exists


From a similar question I used this code to debug the failure of opening a file

echo'<pre>';
error_reporting(E_ALL);
ini_set('display_errors', true);
echo 'phpversion: ', phpversion(), "\n";
echo 'uname: ', php_uname("s r"), "\n"; // name/release of the operating system
//echo 'sapi: ', php_sapi(), "\n";
echo $file, file_exists($file) ? ' exists' : ' does not exist', "\n";
echo $file, is_readable($file) ? ' is readable' : ' is NOT readable', "\n";
echo $file, is_writable($file) ? ' is writable' : ' is NOT readable', "\n";
$fp = @fopen($file, 'x');
if (! $fp) {
    echo 'last error: ';
    var_dump(error_get_last());
}
echo '</pre>

I get this helpful message

D:\data\openid\nonces\4d895d80---2jmj7l5rSw0yVb.vlWAYkK.YBwk-Bk0DdMtjVYDVZi0npvGwNNFSRy0

phpversion: 5.3.1
uname: Windows NT
D:\data\openid\nonces\4d895...FSRy0 exists
D:\data\openid\nonces\4d895...FSRy0 is readable
D:\data\openid\nonces\4d895...FSRy0 is writable
last error: array(4) {
  ["type"]=>
  int(2)
  ["message"]=>
  string(188) "fopen(D:\data\openid\nonces\4d895d80---2jmj7l5rSw0yVb.vlWAYkK.YBwk-Bk0DdMtjVYDVZi0npvGwNNFSRy0) [function.fopen]: failed to open stream: File exists"
  ["file"]=>
  string(38) "D:\web\library\Utils.php"
  ["line"]=>
  int(179)
}

"failed to open stream: File exists" - What could that mean?


Solution

  • This happens because you used the 'x' flag to fopen(). The PHP manual says about it:

    'x' Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.

    You probably want to use fopen($file, 'c') or just the ordinary w mode.