PHP: Create a File on your Server

Posted June 19, 2006 by William_Wilson in PHP programming

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.

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

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.