質問

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

他のヒント

Check with file_exists($filename) if the file exist before you execute your code.

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

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

Using PHP’s is_file function, we check to see if the file already exists or not.

If is_file returns a boolean FALSE value, then our filename does not exist.

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

//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);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top