PHP Create File

Summary: in this tutorial, we will show you various ways to create a new file in PHP.

The fopen() function allows you not only to open an existing file but also to create a new file if it does not exist. If you try open a non-existing file for writing or appending using the fopen() function, PHP creates it for you.

If you want to know how to check if a file exist, you can follow the PHP file exists tutorial.

The fopen() function accepts two parameters:

  • The first parameter is the file name that you want to open.
  • The second parameter is the action that you want to perform on the file.

To create a new file named test.txt for writing in the same directory as the script file, you use the following code:

To create a file and write text into it, you can use the file_put_contents() function. If the file already exists, it will be overwritten.

You don’t have to call the fclose() function to close the file handle because the file_put_contents() function works the same as calling fopen(), fwrite() and fclose() functions in sequence.

  • Was this tutorial helpful ?
  • YesNo