Creating a file?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jrschwartz
Forum Newbie
Posts: 2
Joined: Tue Sep 07, 2004 8:46 am

Creating a file?

Post 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!
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post 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";
}
?>
User avatar
scorphus
Forum Regular
Posts: 589
Joined: Fri May 09, 2003 11:53 pm
Location: Belo Horizonte, Brazil
Contact:

Post 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
jrschwartz
Forum Newbie
Posts: 2
Joined: Tue Sep 07, 2004 8:46 am

Post by jrschwartz »

create a file

it's very possible that I'm wrong but that code does not create a file..
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post 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);
?>
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

touch

Post by neophyte »

You can create a file using touch()[/url]
Post Reply