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

    }

}

4

3 回答 3

1

PHP has a function for that:

file_exists

于 2015-04-23T10:03:49.117 回答
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
于 2015-04-23T10:07:39.097 回答
0

Add a check -

if (file_exists($_SERVER['DOCUMENT_ROOT'].'/path/to/file')) {
    file_put_contents(..);
}
于 2015-04-23T10:10:54.737 回答