PHP Create a File

This article is created to cover multiple scripts/programs in PHP, to create a file.

To create a file in PHP, use any of the following modes:

The last four modes, that are x, x+, c, and c+ only creates a new file, if the specified file does not exits.

PHP Create a File Example

Here is the snapshot of the folder, before executing the PHP script to create a file:

php create file example

Now the PHP script to create a new file is:

<?php
   if(fopen("fresherearth.txt", "w"))
      echo "The file created successfully!";
   else
      echo "The file already exists.";
?>

The output of above PHP example, is:

php create file

And here is the new snapshot of the same folder (current directory) after executing the above PHP script of creating a new file:

php code to create new file

Note - The fopen() opens a file. And w mode given to this function, creates a new file, then opens that file.

PHP Create a File if Not Exists

This article is created to cover a program in PHP, that creates a new file only if the specified file does not exists.

The x mode is used when we need to create a file only if the specified file does not exists. For example:

<?php
   $fs = fopen("fresherearth.txt", "x");
   if($fs)
      echo "The file created successfully!";
   else
      echo "The file already exists.";
?>

Since the file fresherearth.txt already exists in the current directory. Therefore, the output produced by above PHP example, is:

php create file if not exists

The same program can also be created in this way:

<?php
   if(fopen("fresherearth.txt", "x"))
      echo "The file created successfully!";
   else
      echo "The file already exists.";
?>

To hide the default error message, use @ character before the fopen() function. For example:

<?php
   if(@fopen("fresherearth.txt", "x"))
      echo "The file created successfully!";
   else
      echo "The file already exists.";
?>

Now the output produced by above PHP example, is:

php create file if does not exists

Let me tell you again, if specified file does not exists, then a new file with specified name will get created. For example, let me create another example in which I will provide the name of file, that does not exists in the current directory:

<?php
   if(@fopen("temp.txt", "x"))
      echo "The file created successfully!";
   else
      echo "The file already exists.";
?>

Since the file temp.txt is not available in the current directory, therefore temp.txt file will be created, and the output produced by above PHP example should be The file created successfully!

PHP Online Test


« Previous Tutorial Next Tutorial »