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'); fclose($Handle);(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.
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); fclose($Handle);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".)
$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