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!
You can use
fopen()with a mode ofxinstead ofw, which will make fopen fail if the file already exists. The advantage to checking like this compared to usingfile_existsis 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;