PHP - Create file if it doesn’t already exist

  1074 views   1 year ago PHP

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...

//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.
    //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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]