Fwrite if file doesn't exist?

Is it possible to write a file only in PHP if it doesn't exist?

$file = fopen("test.txt","w");
echo fwrite($file,"Some Code Here");
fclose($file);

      

So, if the file exists, the code will not write the code, but if the file does not exist, it will create a new file and write the code

Thanks in advance!

+3


source to share


3 answers


You can use fopen()

with mode x

instead w

, which will make fopen fail if the file already exists. The advantage of checking in this way over using it file_exists

is that it will not behave incorrectly if the file is created between checking for existence and actually opening the file. The downside is that it (somewhat oddly) generates E_WARNING if the file already exists.

In other words (via @ThiefMaster's comment below), something like:



$file = @fopen("test.txt","x");
if($file)
{
    echo fwrite($file,"Some Code Here"); 
    fclose($file); 
}

      

+6


source


Check file_exists ($ filename) if the file exists before you run the code.



if (!file_exists("test.txt")) {
    $file = fopen("test.txt","w");
    echo fwrite($file,"Some Code Here");
    fclose($file); 
}

      

+4


source


Created a variable named $ file. This variable contains the name of the file we want to create.

Using the PHP function is_file, we check if the file exists or not.

If is_file returns the Boolean value FALSE, then our filename does not exist.

If the file does not exist, we create the file using the file_put_contents function.

//The name of the file that we want to create if it doesn't exist.
$file = 'test.txt';

//Use the function is_file to check if the file already exists or not.
if(!is_file($file)){
    //Some simple example content.
    $contents = 'This is a test!';
    //Save our content to the file.
    file_put_contents($file, $contents);
}

      

0


source







All Articles