PHP: Create a File on your Server

Posted June 19, 2006 by admin in PHP programming

Last Updated on

Create an empty file on the server that can be written to.

The handle is the file to be written to, and the filename is of course the name of the file being created. Using these simple commands you can create and add text to your file.

$filename = 'test.txt';
$Content = "Add this to the file\r\n";
echo "open";
$handle = fopen($filename, 'x+');
echo " write";
fwrite($handle, $Content);
echo " close";
if($handle = fopen($filename, 'a')){
if(fwrite($handle, $content) === FALSE){
echo "Cannot write to file $filename";
echo "The file $filename was created and written successfully!";
echo "The file $filename, could not written to!";
echo "The file $filename, could not be created!";

There is a tester commented out here, which displays whether the file was created and/or written to.

The modifier x+ creates a file that is to be written to and still open. There are many more such as a, a+ for appending, and r, r+ for reading.

Questions/Comments: [email protected]
William. ยง (marvin_gohan)

The Conversation

Follow the reactions below and share your own thoughts.