Creating A File Using PHP

by Hiroshi on June 23, 2008

in File, File Manipulation

In PHP, a file is created using a command that is also used to open files. In PHP the fopen function is used to open files. However, it can also create a file if it does not find the file specified in the function call. So if you use fopen on a file that does not exist, it will create it, given that you open the file for writing or appending.

PHP – How to Create a File

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).

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

<?php
$FileName = "testFile.txt";
$FileHandle = fopen($FileName, 'w') or die("can't open file");
fclose($FileHandle);
?>

The file “testFile.txt” should be created in the same directory where this PHP code file is. PHP will see that “testFile.txt” does not exist and will create it after running this code.

Related Posts

Previous post:

Next post: