Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fwrite if file doesn't exist?

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!

like image 281
Flame Trap Avatar asked Dec 22 '22 00:12

Flame Trap


1 Answers

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); 
}
like image 92
Joachim Isaksson Avatar answered Dec 24 '22 03:12

Joachim Isaksson