PHP write file from input to txt - issue - php

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

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.

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

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>';
}
?>

Finding substring when reading from an uploaded file fails

Why can't I do a proper strpos function on an uploaded file (I first upload the file, and then do a $site = stream_get_line($f, 4096, "\n")) and it works completely fine when read the same thing into $site from a manually created file on the server.
I have no idea what's causing it... it seems to read the line well in both cases, but strpos just doesn't work the same when it's uploaded via user versus when I create it manually.
Here's the code:
<?php
if(!$_FILES){
?>
<head>
<title>Bulk Index Checker</title>
</head>
<center>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br/>
<input type="submit" value="Check 'em!" />
</form>
</center>
<?php
}
else{
echo("<center> <h1>Checking... please wait.</h1> <br><table border=1> <tr><td>Site</td><td>Indexed</td></tr>");
$target_path = "checkupload/";
$target_path = $target_path . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $target_path);
$f = fopen($target_path, "r") or exit("Unable to open file!");
while (!feof($f))
{
$site = stream_get_line($f, 4096, "\n");
$url = 'http://www.google.com/search?q=info:' . $site;
//sleep(3);
$contents = file_get_contents($url);
if (strpos($contents,'<h3 class="r"><a href="/url?q='.$site)!=FALSE) {
echo("<tr bgcolor=\"Silver\"><td>".$site."</td><td>YES</td></tr>");
echo("<br>");
}
else{
echo("<tr><td>".$site."</td><td>NO</td></tr>");
}
}
?>
</table>
<br/>
<form>
</center>
<?php
}
?>
Edit: Here's another way I tried (using textarea) - same thing basically - it ONLY works properly when you input only 1 URL. As soon as you input another URL below, it shows a FALSE for the first one when it's really TRUE.
WHY IS THIS HAPPENING?
<?php
if(!$_POST){
?>
<head>
<title>Bulk Index Checker</title>
</head>
<center>
<h1>Bulk Index Checker v1.0</h1>
<form method="post" enctype="multipart/form-data">
<textarea id="list" name="list" rows="10" cols="50"></textarea>
<br/>
<input type="submit" value="Check 'em!" />
</form>
</center>
<?php
}
else{
echo("<center> <h1>Checking... please wait.</h1> <br><table border=1> <tr><td>Site</td><td>Indexed</td></tr>");
$lines = explode("\n", $_POST['list']);
foreach($lines as $site) {
echo($site);
$url = 'http://www.google.com/search?q=info:' . $site;
sleep(3);
$contents = file_get_contents($url);
if (strpos($contents,'<h3 class="r"><a href="/url?q='.$site)!=FALSE) {
echo("<tr bgcolor=\"Silver\"><td>".$site."</td><td>YES</td></tr>");
echo("<br>");
}
else{
echo("<tr><td>".$site."</td><td>NO</td></tr>");
}
}
?>
</table>
<br/>
</center>
<?php
}
?>
Try to use '!==' instead of '!='.
I don't have an option to test at this stage. See http://php.net/manual/en/function.strpos.php (example #2)

how to save .html file by PHP by save as button?

I've created a PHP file which shows the results from a MySQL database as we all create like in
echo "<table><tr><td>";
...
echo "</td></tr></table>";
But now I want to make a button at the bottom of the table, something like 'save report', which saves the created table into HTML format.
So how could it be done?
You can use the following scripts:
index.php
In index.php, you have the HTML table.
<?php
$contents = "<table><tr><td>A</td><td>B</td></tr><tr><td>One</td><td>Two</td></tr><tr><td>Three</td><td>Four</td></tr></table>"; // Put here the source code of your table.
?>
<html>
<head>
<title>Save the file!</title>
</head>
<body>
<?php echo $contents; ?>
<form action="savefile.php" method="post">
<input type="hidden" name="contents" value="<?php echo htmlspecialchars($contents); ?>">
<input type="submit" value="Save file" />
</form>
</body>
</html>
savefile.php
And then use the file savefile.php to popup your browser's download dialog to save the file.
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
header('Content-type: text/html');
header('Content-Disposition: attachment; filename="table.html"');
echo $_POST['contents'];
}
?>
I think you want to save reports generated by PHP/MySQL as HTML file?
<?php
// Open file for writing
$fileHandle = fopen("/DestinationPath/DestinationFile.html", "w");
// Dump File
$head = "<html><head><title>my reports</title></head><body>\n";
fwrite($fileHandle, $head);
$sql = mysql_query("Your sql query here");
while ($result = mysql_fetch_assoc($sql)) {
$line = $result['yourmysqlfield']."\n";
fwrite($fileHandle, $line);
}
$foot = "</body></html>\n";
fwrite($fileHandle, $foot);
// Close File
close($fileHandle);
?>

Categories