PHP: Create file if it doesn’t already exist.

In this tutorial, we will use PHP to check if a file exists before we attempt to create it. This is particularly useful if you only want create the file once (for file caching purposes, etc). i.e. You want 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.
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 PHP code above:

  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.

That’s it! It’s as simple as that!