Search code examples
phpfilefile-put-contents

Best way to check if a file exists before execute a file_put_contents function


As the title says I'm searching for the best way to check if a file exists before execute a file_put_contents function. It's better to add a number after the filename? or It's better to generate the filename with a date/time after the name? In my case, what would you do?

Here's my working code,

if(isset($_POST['genfile'])){

  $scriptfile = $_POST['genfile'];

  $script = preg_split('/(\r?\n)+/', $_POST['genfile']);
  $copy=$script;



         file_put_contents('generated_scripts/script.sh', $scriptfile);

         foreach ($script as $script_launcher){

          echo $script_launcher;

            if (next($copy)) {
              echo "\r\n";
            }                                 

    }

}


Solution

  • To check if file exists you can use built up function file_exists in php.

    Example :

    if (file_exists($file)) {
        //file exists                       
    }
    

    Alternatively you can use get_headers function.

    Example:

    $headers = @get_headers($filename);
    $exists = ($headers[0] == 'HTTP/1.1 404 Not Found'); //file does not exist