How to Create a File in PHP

php create file

File Create

The fopen function needs two important pieces of information to operate correctly. First, we must supply it with the name of the file that we want it to open. Secondly, we must tell the function what we plan on doing with that file (i.e. read from the file, write information, etc).

Since we want to create a file, we must supply a file name and tell PHP that we want to write to the file. Note: We have to tell PHP we are writing to the file, otherwise it will not create a new file.

$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");


The file “testFile.txt” should be created in the same directory where this PHP code resides. PHP will see that “testFile.txt” does not exist and will create it after running this code. There’s a lot of information in those three lines of code, let’s make sure you understand it.

1.$ourFileName = “testFile.txt”;

Here we create the name of our file, “testFile.txt” and store it into a PHP String variable $ourFileName.

2.$ourFileHandle = fopen($ourFileName, ‘w’) or die(“can’t open file”);

This bit of code actually has two parts. First we use the function fopen and give it two arguments: our file name and we inform PHP that we want to write by passing the character “w”.

Second, the fopen function returns what is called a file handle, which will allow us to manipulate the file. We save the file handle into the $ourFileHandle variable. We will talk more about file handles later on.


We close the file that was opened. fclose takes the file handle that is to be closed.

You may also like...