-2

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";
            }                                 

    }

}

JBoY
  • 51
  • 3
  • 13

3 Answers3

1

PHP has a function for that:

file_exists

Matheno
  • 4,112
  • 6
  • 36
  • 53
1

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
JTC
  • 3,344
  • 3
  • 28
  • 46
0

Add a check -

if (file_exists($_SERVER['DOCUMENT_ROOT'].'/path/to/file')) {
    file_put_contents(..);
}
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87