book musings



missle defense



cultcha blog


scripts & programs

on the town



creds (PDF)



PHP: Creating a File on Disk

The PHP command for both creating and opening a file is "fopen" ... Like typical Unix file programs, if it doesn't see a file called "x" it will create a file called x.

How to create a disk file using PHP? This tutorial advises us to add these three lines to a PHP skeleton file:

$Name = "ThisFileWasCreatedByPHP.txt";
$Handle = fopen($Name, 'w');
(For the full working code, click here. To get the code to run in a PHP environment, change the "txt" suffix to "php".)

All you do to execute this action of creating a file is to call up this page with a browser. The page should have a suffix of .php (i.e. "01-CreateFile.txt.php") and you should have PHP working on your server.

NOTE: For this to work, the administrator must give "all" user permissions for reading, writing and executing programs for the directory this file is in. Sucks, I know. In other words, don't use this in a directory with any valuable info (at the command line, type "chmod a+rwx [Name of Directory]")

In the above code, the tutorial tutors us, the first line creates a name of the file ("ThisFileWasCreatedByPHP.txt"") and assigns it to a variable ($Name).

The second line instructs PHP to open and write ("w") to a file, or if one doesn't exist, create that file, with the "fopen" command, giving it the name of variable $Name (which in this case, happens to be "ThatThatWasCreatedByPHP.txt"). The third line closes the file.

Now, that we have learned how to create and open a disk file with PHP, now it's time to write something to it.

Again referring to this tutorial, we insert two lines into the previous set of code:

$Name = “FileToAddStuffTo.txt”;
$Handle = fopen($Name, ‘w’);

$TextToAdd = "HelloWorld\n";
fwrite($Handle, $TextToAdd);

The new part is here:
$TextToAdd = "HelloWorld\n";
fwrite($Handle, $TextToAdd);
The PHP "fwrite" command is key here. With it, you are instructing PHP to 1: open the file “FileToAddStuffTo.txt” (which has been assigned to the variable $Name, and is opened by calling the variable $Handle), and 2: write into the file the contents of variable $TextToAdd).

(For the full working code, click here. To get the code to run in a PHP environment, change the "txt" suffix to "php".)

Running the above code, you will just overwrite what was previously there. Appending a file requires an different flag. Instead of this:
$Handle = fopen($Name, ‘w’);
you'd write this:
$Handle = fopen($Name, ‘a’);
Also, be sure to add a new line break at the end of the string ("\n"):
$TextToAdd = "HelloWorld\n";
For this sample, I used PHP 5.2.4