Click to See Complete Forum and Search --> : Create File using PHP


aaronking
September 14th, 2006, 01:22 AM
hello..

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?

blueday54555
September 14th, 2006, 03:44 AM
check-out "fopen" on php.net for this
http://de2.php.net/manual/en/function.fopen.php

PeejAvery
September 14th, 2006, 09:10 AM
And after that you will need fwrite() (http://de2.php.net/manual/en/function.fwrite.php).

Here is the example code from that page.
<?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";
}
?>

bubu
September 22nd, 2006, 07:49 AM
If you use PHP 5, try this (not tested):


<html>
<head><title>Create Files</title></head>
<body>
<?php
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">
</form>';
?>

</body>
</html>