PHP: Create a File on your Server

Contributor Icon Contributed by William_Wilson  
Tag Icon Tagged: 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);
 

?>

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: william_a_wilson@hotmail.com
William. ยง (marvin_gohan)

 

2 Comments -


  1. andy said on November 21, 2008

    you are missing a “)” on this line :

    if(is_writable($filename){

    Should read
    if(is_writable($filename)){

  2. Quinn McHenry said on November 21, 2008

    Thanks andy — I’ve fixed the post.

 

RSS feed for comments on this post. TrackBack URL

Leave a comment -