Page 1 of 1

Creating a file?

Posted: Tue Sep 07, 2004 8:48 am
by jrschwartz
Would like to know the little bit of code needed to create a file in php.

I obviously need to have the permissions set in the folder.

But what is the code to create a file..

vars:
$TEXT = message text..
$FILENAME = filename.

etc.

Thanks!

Posted: Tue Sep 07, 2004 8:56 am
by CoderGoblin
Before asking it would be polite if you had a basic look at the php manual. The code pasted below is a direct copy of a sample within the manual... http://www.php.net/manual/en/function.fwrite.php

Code: Select all

<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

   // In our example we're opening $filename in append mode.
   // The file pointer is at the bottom of the file hence
   // that's where $somecontent will go when we fwrite() it.
   if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
   }

   // Write $somecontent to our opened file.
   if (fwrite($handle, $somecontent) === FALSE) {
       echo "Cannot write to file ($filename)";
       exit;
   }
  
   echo "Success, wrote ($somecontent) to file ($filename)";
  
   fclose($handle);

} else {
   echo "The file $filename is not writable";
}
?>

Posted: Tue Sep 07, 2004 8:58 am
by scorphus
RTM! You might want to start here: Filesystem Functions. Then pay special attention to [php_man]fopen[/php_man]() and [php_man]fwrite[/php_man]() functions' reference.

-- Scorphus

Posted: Tue Sep 07, 2004 9:03 am
by jrschwartz
create a file

it's very possible that I'm wrong but that code does not create a file..

Posted: Tue Sep 07, 2004 9:08 am
by CoderGoblin
OK you are right, first code just writes to existing file... fopen requires the 'w' parameter and you can ignore the error checks.

Code: Select all

$handle = fopen($fname, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);
unlink($fname);
?>

touch

Posted: Tue Sep 07, 2004 10:27 am
by neophyte
You can create a file using touch()[/url]