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 to 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:

<?php $filename = 'test.txt'; $handle = fopen($filename, 'w') or die('cannot open the file'); fclose($handle);
Code language: HTML, XML (xml)

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.

<?php $filename = 'test.txt'; $content = 'This is for file content'; $handle = file_put_contents($filename,$content);
Code language: HTML, XML (xml)

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

Did you find this tutorial useful?