PHP code to create a file

This article is created to cover multiple scripts or programs in PHP to create a file. To create a file in PHP, use any of the following modes:

The last four modes, which are x, x+, c, and c+, only create a new file if the specified file does not exit.

PHP Create a File Example

Here is a 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("codescracker.txt", "w"))
      echo "The file created successfully!";
   else
      echo "The file already exists.";
?>

The output of the above PHP example is:

php create file

After running the above PHP script to make a new file, here is a snapshot of the same folder (the current directory):

php code to create new file

Note: The fopen() function opens a file. And with the "w" mode given to this function, it creates a new file and then opens that file.

Create a file if it doesn't exist in PHP

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

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

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

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

php create file if not exists

The same program can also be created in this way:

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

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

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

Now the output produced by the above PHP example is:

php create file if does not exists

Let me tell you again: if the specified file does not exist, a new one with the specified name will get created. For example, let me create another example in which I will provide the name of a file that does not exist 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, it will be created, and the output produced by the above PHP example should be "The file created successfully!"

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!