Tags: box, create, enter, file, page, php, phpi, programming, text

Create File using PHP

On Programmer » Programming Misc

2,362 words with 3 Comments; publish: Sun, 10 Feb 2008 01:20:00 GMT; (200109.38, « »)


just wondering how do you create a file using php?

I have a text box on a page and I want to make it when you enter something making it create a file on my website called what ever is in the text box.

For Example:

I type in 'test' in the textbox and when I click the submit button making it create the 'test' file with .txt at the end. (test.txt)

any ideas?

All Comments

Leave a comment...

    • check-out "fopen" on php.net for this


      #1; Sat, 10 Nov 2007 03:57:00 GMT
    • And after that you will need fwrite() (http://de2.php.net/manual/en/function.fwrite.php).

      Here is the example code from that page.


      $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)";



      // Write $somecontent to our opened file.

      if (fwrite($handle, $somecontent) === FALSE) {

      echo "Cannot write to file ($filename)";



      echo "Success, wrote ($somecontent) to file ($filename)";


      } else {

      echo "The file $filename is not writable";



      #2; Sat, 10 Nov 2007 03:58:00 GMT
    • If you use PHP 5, try this (not tested):


      <head><title>Create Files</title></head>



      if (isset($_POST['filename'])) {

      $myfile = urlencode($_POST['filename']);

      $mycontent = urlencode($_POST['filecontent']);

      file_put_contents($myfile, $mycontent);

      echo 'File created sucessfuly!';


      echo '<form action="'.$_SERVER['PHP_SELF'].'">

      File name: <input type="text" name="filename"><br>

      File content: <input type="text" name="filecontent"><br>

      <input type="submit" value="Submit">





      #3; Sat, 10 Nov 2007 03:59:00 GMT