Php – fwrite if file doesn’t exist

fclosefopenfwritephp

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

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

So if the file does exist the code won't write the code but if the file doesn't exist it will create a new file and write the code

Thanks in advance!

Best Solution

You can use fopen() with a mode of x instead of w, which will make fopen fail if the file already exists. The advantage to checking like this compared to using file_exists is that it will not behave wrong if the file is created between checking for existence and actually opening the file. The downside is that it (somewhat oddly) generates an E_WARNING if the file already exists.

In other words (with the help of @ThiefMaster's comment below), something like;

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