Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The obvious solution would be to call <a href="http://us2.php.net/manual/en/function.file-exists.php" rel="nofollow noreferrer">file_exists</a> to check to see if the file exists, but doing that could cause a race condition. There is always the possibility that the other file will be created in between when you call <a href="http://us2.php.net/manual/en/function.file-exists.php" rel="nofollow noreferrer">file_exists</a> and when you call <a href="http://us2.php.net/manual/en/function.copy.php" rel="nofollow noreferrer">copy</a>. The only safe way to check if the file exists is to use <a href="http://us2.php.net/manual/en/function.fopen.php" rel="nofollow noreferrer">fopen</a>.</p> <p>When you call <a href="http://us2.php.net/manual/en/function.fopen.php" rel="nofollow noreferrer">fopen</a>, set the mode to 'x'. This tells <a href="http://us2.php.net/manual/en/function.fopen.php" rel="nofollow noreferrer">fopen</a> to create the file, but only if it doesn't exist. If it exists, <a href="http://us2.php.net/manual/en/function.fopen.php" rel="nofollow noreferrer">fopen</a> will fail, and you'll know that you couldn't create the file. If it succeeds, you will have a created a file at the destination that you can safely copy over. Sample code is below:</p> <pre><code>// The PHP copy function blindly copies over existing files. We don't wish // this to happen, so we have to perform the copy a bit differently. The // only safe way to ensure we don't overwrite an existing file is to call // fopen in create-only mode (mode 'x'). If it succeeds, the file did not // exist before, and we've successfully created it, meaning we own the // file. After that, we can safely copy over our own file. $filename = 'sourcefile.txt' $copyname = 'sourcefile_copy.txt' if ($file = @fopen($copyname, 'x')) { // We've successfully created a file, so it's ours. We'll close // our handle. if (!@fclose($file)) { // There was some problem with our file handle. return false; } // Now we copy over the file we created. if (!@copy($filename, $copyname)) { // The copy failed, even though we own the file, so we'll clean // up by itrying to remove the file and report failure. unlink($copyname); return false; } return true; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload