Creating files with PHP




To create a file in PHP you use the fopen function, this is the same function that is used to open files but if it does not find the file specified it will create a brand new file for you.

fopen requires 2 things, firstly it has to know the name of the file that you wish to open then secondly it requires to know how you plan to access it, for example read only would allow reading of the file but you could not add more data or write to the file.

In the case of creating a file we specify a file that does not already exist and the fact we wish to write to it, lets look at an example.

 

$file = fopen("myfile.txt","w") or die("CANNOT CREATE FILE");
fclose($file);

 

The example above will create the file called myfile.txt in the same directory as the script that this is run from

 

Lets look at the code line by line

 

Line 1 : This creates a file handle called $file, we then create (because the file doesn't already exist) called myfile.txt and then we say that we wish to write to this file , if this cannot be done we display an error message to the user.


Line 2 : We close the file handle $file