Create a file server side via a simple PHP/HTML page - php

I am trying to create a HTML/PHP file in which a user inputs a file name to a text box, clicks submit, then that file is created in the same file folder in the directory
Here is what I have so far, Unfortunatley this my 3rd of fourth attempt, deleting and restarting. I cannot promise it is the best version
<?php
function addExtension($fileName) {
return ($file) + ".txt";
}
if (isset($_POST['prefix'])) {
$result = ($file), (intval($_POST['prefix']));
}
$ourFileName = addExtension;
$ourFileHandle = fopen($fileName, 'w') or die("can't open file");
fclose($ourFileHandle);
?>
<html>
<body>
<?php if (isset($result)) { ?>
<h1> Result: <?php echo $result ?></h1>
<?php } ?>
<form action="" method="post">
<p>File name of file to be created <input type="text" name="prefix" /></p>
<p><input type="submit"/></p>
</body>
</html>
Im not even sure If I'm on the track any more, any help would be great,
Thanks
UPDATE!!!
With the help of the answers below and a few hours I believe I am getting somewhere, But still not 100% there.
Here is what I have.
<html>
<head>
<title>File Creation</title>
<?PHP
$prefix = $_POST['prefix'] ;
$extension = ".css" ;
$ourFileHandle = fopen($prefix, 'w') or die("can't open file");
fclose($ourFileHandle);
?>
</head>
<body>
<FORM NAME ="form1" METHOD ="POST" ACTION = "basicForm.php">
<INPUT TYPE = "TEXT" VALUE ="username" NAME="prefix">
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login">
</FORM>
</body>
</html>
It works as I expect and desire. the issue I'm having is creating the function to combine "$prefix and $extension". I know its something simple, and I have been over it in tutorials previously but which ones I cannot seem to find for the life of me. any more help would be much appreciated!
Just if anyone is curious my intention eventually is to have the script create a file within a folder of the same name, inside a specified folder. The file will be a css file and the contents dynamically changed through the same form.
Thanks Again!
Solved it
Below is the final code/
<html>
<head>
<title>File Creation</title>
<?PHP
if ( isset( $_POST['Submit1'] ) ) {
$prefix = $_POST ['prefix'] ;
$extension = ".css" ;
print "File " .$prefix . $extension . " Created";
$ourFileHandle = fopen($prefix . $extension, 'w') or die("can't open file");
fclose($ourFileHandle);
}
?>
</head>
<body>
<FORM NAME ="form1" METHOD ="POST" ACTION = "fileCreationFormV2.php">
<INPUT TYPE = "TEXT" VALUE ="File Name" NAME="prefix">
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Create">
</FORM>
</body>
</html>
I was looking over an old contact form id created and it hit me " . ".
Thanks to everyone for their help!

In your function,
function addExtension($fileName) {
return ($file) + ".txt"; // here you cannot call $file, you can call $fileName
}
I didn't understand your this line
$result = ($file), (intval($_POST['prefix']));
In this line
$ourFileName = addExtension; // you have to call like addExtension('your file name goes here')
Then,
$ourFileHandle = fopen($fileName, 'w') or die("can't open file");
It should be
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");

<?php
if(isset($_POST['prefix'])) {
$prefix=$_POST['prefix'];
$filename=$prefix . '.txt';
$ourFileHandle=fopen($fileName, 'w') or die("can't open file");
echo 'done!';
fclose($ourFileHandle);
}
else
{
echo '<html>
<body>
<form action="" method="post">
<p>File name of file to be created <input type="text" name="prefix" /></p>
<p><input type="submit"/></p>
</body>
</html>';
}
?>

Related

PHP form to store data in text file not working

My simple PHP code is not working and I dont know why.
<html>
<head></head>
<body>
<form action="phpform.php" method="post">
<label for = "name">Name : </label>
<input type="text" name="name" required><br>
<input type="submit">
</body>
</html>
<?php
if(isset($_POST['name']))
{
$names=$_POST['name'];
$fp = fopen('txtfiles/FirstNames.txt', 'a');
fwrite($fp, $names);
fclose($fp);
}
After pressing "Submit" button webpage resets (as it should), but when I open "FirstNames.txt" it is empty. No error messages, no nothing.
Thank You for Your help.
Try something like this
Add this so we can see what is happening
<pre>
<?= print_r($_POST, true) ?>
</pre>
<?php
if ( isset($_POST['name']) )
{
$names = $_POST['name'];
$file = 'txtfiles/FirstNames.txt'; // put file name in its own variable
if ( ! file_exists($file) ) {
// File should already exist
throw new Exception('File does not exist');
}
echo realpath($file); // where is it really?
$fp = fopen($file, 'a');
if ( ! $fp ) {
throw new Exception('Unable to open file');
}
fwrite($fp, $names);
fclose($fp);
} else {
echo "\$_POST['name'] does not exist";
}

Trouble Writing back to text file using PHP fwrite from file selected from a dropdown form

I am having trouble writing back to a text file selected from a html form with a dropdown menu, the script is able to read but is unable to write back, returns "Unable to Open File".using PHP fopen and fwrite
This is the index.html code:
<html>
<head></head>
<title>Edit Server Side Text Files</title>
<body>
<form action="function.php" method="post">
<select name="list">
<option value="./files/banned-kdf.txt">banned-kdf.txt</option>
<option value="./files/blackList.txt">blackList.txt</option>
</select>
<input type="submit" name="edit" value="Edit" />
</form>
</body>
</html>
And this is the function.php code:
<?php
if(isset($_POST["edit"])) {
$filename = $_POST["list"];
global $filename;
// var_dump($filename);
$myfile = fopen("$filename", "r") or die("Unable to open file!");
$filecontent = fread($myfile,filesize("$filename"));
fclose($myfile);
}
?>
<html>
<form action="<?php echo $PHP_SELF;?>" method="post">
<textarea name="textareaContent" rows="50" cols="100">
<?
if(isset($filecontent)) { echo $filecontent; }
?>
</textarea>
<br>
<br>
<input type="submit" name="update" value="Update" />
</textarea>
<?
//write to text file
if(isset($_POST["update"])) {
// The following two lines are just for troubleshooting and have been commented out.
// echo $_POST["update"];
// var_dump($filename);
$myfile = fopen("$filename", "w") or die("Unable to open file!");
fwrite($myfile, $_POST["textareaContent"]);
fclose($myfile);
}
?>
</form>
<br>
<br>
Return to List Selection
</html>
You're not sending file name in the second form, just code, so, $filename is undefined. Add it in an input hidden:
global $variable; is not useful here, because the variable will not be present on next script execution, when processing the form.
<?php
// Default value for contents:
$filecontent = '';
// Ok, read the file here
if(isset($_POST["edit"])) {
$filename = $_POST["list"];
global $filename; // This will not be useful
$myfile = fopen("$filename", "r") or die("Unable to open file!");
$filecontent = fread($myfile,filesize("$filename"));
fclose($myfile);
}
// If request comes from second form, process it
if(isset($_POST['update'])) {
// Get file name from input hidden
$filename = $_POST["filename"];
$myfile = fopen("$filename", "w") or die("Unable to open file!");
fwrite($myfile, $_POST["textareaContent"]);
fclose($myfile);
// End the script, no need to show the form again
die('File updated successfully.');
}
?>
<html>
<form action="<?php echo $PHP_SELF;?>" method="post">
<input type="hidden" name="filename" value ="<?php
// Send filename within form
echo $filename;
?>">
<textarea name="textareaContent" rows="50" cols="100">
<?
// No if needed here, we already have a value
echo $filecontent;
?>
</textarea>
<br>
<br>
<input type="submit" name="update" value="Update" />
</form>
<br>
<br>
Return to List Selection
</html>
Please check the permission of target file and the folder in this the file is supposed to be.

PHP write file from input to txt - issue

I've been at this for a while and been through other options on stack but can't get this to work. (I'm pretty nooby, sorry!)
I have a form which i want to send data to my txt file but it's just not writing.
ANY help greatly appreciated, thank you!!
My HTML Form:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>php test</title>
</head>
<title></title>
</head>
<body>
<form action="myprocessingscript.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='/tmp/mydata.txt'>Text file</a>
</body>
And my PHP
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = fwrite('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
You need to open a file before you can write to it with fwrite().
$fp = fopen('/tmp/mydata.txt', 'w');
$ret = fwrite($fp, $data);
//and don't forget to close it
fclose($fp);
if($ret === false) {
...
Based on the flags you use in the question I think the function you might be thinking of is file_put_contents (See Docs HERE) and not fwrite.
Try to add this line of code:
$myfile = fopen("/tmp/mydata.txt", "w") or die("Unable to open file!");
before the fwrite(), then you can now insert data/text in your file:
fwrite($myfile, $data);

Save text from URL

I found this code. He saves a text file on the server
I want to change it instead to have a textBox and button.
Have the possibility to compose the URL
Example:
www.example.com/index.php?writeText=text
What needs to change in this code to do this?
<html>
<body>
<form name="form" method="post">
<input type="text" name="text_box" size="50"/>
<input type="submit" id="search-submit" value="submit" />
</form>
</body>
<?php
if(isset($_POST['text_box'])) { //only do file operations when appropriate
$a = $_POST['text_box'];
$myFile = "t.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $a);
fclose($fh);
}
?>
Thanks
You use GET instead of POST.
<?php
if(isset($_GET['writeText'])) { //only do file operations when appropriate
$a = $_GET['writeText'];
$myFile = "t.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $a);
fclose($fh);
}
?>

Edit a file with PHP

Ok here is what I have going on.
I am listing the contest of a directory so I can edit and delete files.
The code I am using to do that is below (Other then editing as it does not work).
<?php
$directory = ("enctlfiles/");
$dir = opendir($directory);
$files = array();
while (($file = readdir($dir)) != false) {
$files[] = $file;
}
closedir($dir);
sort($files);
print("<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n");
print("<TR><TH>File Name</TH><th>Modified Date</th><th>Entries In File</th><th>Delete | Edit</th></TR>\n");
foreach ($files as $file)
{
if (strpos($file, '.jpg',1)||strpos($file, '.ctl',1) ){
echo "<TR><TD><a href=$directory$file>$file</a></td>";
echo "<td>";
echo date("F d Y H:i:s",filemtime($directory. $file));
echo "<td>";
echo count(file($directory. $file));
echo "<td>";
echo "<a href=enctlfiles/dodelete.php?file=$file>Delete</a> | <a href=enctlfiles/editfile.php?file=$file>Edit</a>";
}
}
?>
That lists all of the files in order in a nice pretty table. The delete function works. The edit one not so much . It is due to me not knowing what I am doing I am sure of it.
Here is the contents of the editfile.php
<form action="edit.php" method="post">
<TEXTAREA NAME="save" COLS=150 ROWS=50 wrap="off">
<?php
$dir = ".";
include($dir. '/' .$_GET['file']);
?>
</textarea>
<P><INPUT TYPE="SUBMIT" VALUE="Update File"><INPUT TYPE="RESET">
</FORM>
That populates the textarea with the file contents when you click on the "Edit" link. I don't know if that is the right way to get the data in there to be able to edit the file.
Here is the contents of the edit.php file:
<?php
//I have tried this but it give me that Unable to open file.
//$org = ($_GET['file']) or exit("Unable to open file!");
//This returns me to the prodsh.php page but does not edit the file.
$org = $_POST['save'] or exit("Unable to open file!");
$copy = $org . date("-m-d-Y-His");
copy($org,$copy);
$f = fopen($org, 'w');
fwrite($f, $_POST['save']);
fclose($f);
header('Location: http://somesite.com/GroveTuckey/itemsetup/prodsh.php');
?>
I think the editfile.php and the edit.php file are jacked up but don't know where.
I am trying to learn this and this site has been very helpful when I get stumped on something so I thank you in advance for the help given.
Also I know the danger of editing files via a webpage. This is not public or on a server that is accessible by the world. Right now I don't want to deal with a database.
I have edited files using the below code:
<form action="doedit.php" method="post">
<TEXTAREA NAME="save" COLS=150 ROWS=50 wrap="off">
<?php
include('somefile.ctl');
?>
</textarea>
<P><INPUT TYPE="SUBMIT" VALUE="Update File"><INPUT TYPE="RESET">
</FORM>
With the contents of doedit.php being:
<?php
$org = 'Somefile.ctl';// This is the name of the file in the form above
$copy = $org . date("-m-d-Y-His");
copy($org,$copy);
$f = fopen('somefile.ctl', 'w');//This is the name of said file also.
fwrite($f, $_POST['save']);
fclose($f);
header('Location: http://somesite.com/GroveTickey/editfile.php');
?>
But since the names of the files can be anything I can't put specific names in the script.
This works great other then having to hardcode file names.
You aren't passing the name of the file back to edit.php. Set the form's action to edit.php?file=<?php echo $_GET['file']; ?>.
El codigo para editar lo hice asi:
---Inicio
<? php
$filename = isset($_GET['file']) ? $_GET['file'] : '';
$directory = ("C:\\Linux\\www\\contenido\\"); // Restrict to this directory...
$fn = $directory . $filename;
if (isset($_POST['content']))
{
$content = stripslashes($_POST['content']);
$fp = fopen($fn,"w") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
}
?>
<form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post">
<textarea rows="25" cols="100" name="content"><?php readfile($fn); ?></textarea>
<hr />
<input type="submit" value="Guardar">
</form>
back to list
And work great

Categories