Site Admin
Site Admin Founder of MeaningArticles
86 Views

PHP Create file if it doesn’t already exist

Hello Dev.

In this article, we will use PHP to check if a file exists before we strive to create it. that is specially beneficial in case you simplest need create the file as soon as (for file caching functions, and so forth). i.e. You need to avoid any unnecessary writes to the disk.

In this guide, we will be creating a simple text file called test.txt...
test.txt

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

In the above PHP test.txt file...

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

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

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

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

i'm hoping it assist you to, thanks for visit my article if you like my article then proportion together with your friend and social platform.