I have this PHP file, which will write the text to a file:
<?php
$file = 'something.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new line to the file
$current .= "Some Text\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>
But how do I make it so it takes the text from a input tag instead?
I am not very good at PHP, so sorry if it is obvious to you :(
html:
<form action="example.php">
<input type="text" name="field">
<input type="submit" value="Submit">
</form>
PHP:
<?php
if (isset($_GET['field'])) {
$file = 'something.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new line to the file
$current .= "\n".$_GET['field'];
// Write the contents back to the file
file_put_contents($file, $current);
}
?>
or you can use the append flag mentioned in the previous comments.
Assume you have a form in your webpage:
<form action="write.php" method="post">
<input type="text" name="field">
<input type="submit" value="Submit">
</form>
Then in your "write.php" should have this:
<?php
$file = 'something.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new line to the file
$current .= $_POST["field"];
$current .= "\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>
Related
I want to make an html document update with input from a form
The goal is to be able to enter the URL, enter the description, enter the date created and output to a file.
My thoughts are to break the HTML document into pieces, begin.txt newarticle.txt and end.txt
Then piece it back together using fopen and fwrite.
I'm sure there's an easier way, but this is how I'm currently trying to do it.
<html>
<body bgcolor="#FFFFFF>
<H1>Add new Article</h1>
<form action="newarticle.php" method="post">
Paste the link address
<input type="text" name="url">
</br>
Paste the description:
<input type="text" name="description">
</br>
Paste the date article was released:
<input type="text" name="date">
<p>
<input type=submit value="Create Article">
</form>
</body>
</html>
newarticle.php
<?php
$v1 = $_POST["url"]; //You have to get the form data
$v2 = $_POST["description"];
$v3 = $_POST["date"];
$file = fopen('newarticle.txt', 'w+'); //Open your .txt file
ftruncate($file, 0); //Clear the file to 0bit
$content = $v1. PHP_EOL .$v2. PHP_EOL .$v3;
fwrite($file , $content); //Now lets write it in there
fclose($file ); //Finally close our .txt
die(header("Location: ".$_SERVER["HTTP_REFERER"]));
?>
This gives me the output on three separate lines.
How do I have it create a file with content formatted it into an actual piece of code :
<li><a href=$v1>$v2</a></li>
<li>$v3</li>
If you don't mind the format of the html always being exactly the same with the same set of elements, but different attribute values and inner HTML, you can use a heredoc to build up the html. Basically a multi-line string. For example:
$v1 = "info from the form";
$v2 = "more info!";
$built = <<<EOF
<li>$v1</li>\n
<li>$v2</li>
EOF;
echo $built;
this will output:
<li>info from the form</li>
<li>more info!</li>
I am trying to get information from textarea to be converted to a .py file.
Here's my file https://jsfiddle.net/girlwhocancode/68mb49gq/
<form action=action.php method="post">
<center>
<textarea placeholder="Code you want to execute in python..."></textarea>
</center><br/>
<center><input type="submit" class="button_example"></center>
</form>
and this is my php file:
<?php
$path = #PATH;
if (isset($_POST['field1'])) {
$fh = fopen($path,"a+");
$string = $_POST['field1'];
fwrite($fh,$string); // Write information to the file
fclose($fh); // Close the file
}
?>
For some reason my php isn't working and I have no idea how to keep the same webpage after submitting
Try this:
<form action="action.php" method="post">
<center>
<textarea name="script" placeholder="Code you want to execute in python..."></textarea> //added name
</center><br/>
<center><input name="submit" type="submit" class="button_example"></center>
</form> // added name submit
in php
<?php
$path = #PATH;
if (isset($_POST['submit'])) {
$fh = fopen($path,"a+");
$string = $_POST['script'];
fwrite($fh,$string); // Write information to the file
fclose($fh); // Close the file
}
?>
Remember that in php $_POST/$_GET keys are always your form field
names
I want to use fwrite to save data into a .txt file. The action method seems to be working, as it can show HTML tags when being transfered when pressing submit, but i wont run the PHP.
<HTML lang="da">
<style>
</style>
<header>
<title>Tilføj</title>
<meta charset="ISO-8859-1">
</header>
<body>
<form method="post" action="eksamen_save_data.php" enctype='multipart/form-data'>
<fieldset>
<legend>Filmoplysninger</legend>
<div><label>Titel: <input type="text" name="titel" id="titel" required="required" size="60" maxlength="100"></label></div>
<div><label>Hovedskuespiller: <input type="text" name="hovedskuespiller" id="hovedskuespiller" required="required" size="30" maxlength="100"></label></div>
<div><label>Genre: <input type="text" name="genre" id="genre" required="required" size="60" maxlength="100"></label></div>
<div><label>Format: <input type="text" name="format" id="format" required="required" size="60" maxlength="100"></label></div>
<div><label>Billede: <input type="file" name="billede" id="billede" required="required"></label></div>
</fieldset>
<div><input type="submit" id="ok" value="OK"></div>
</form>
</body>
This sends it to the "eksamen_save_data.php" that looks like this:
<?php
$Titel = $_POST["titel"];
$Hovedskuespiller = $_POST["hovedskuespiller"];
$Genre = $_POST["genre"];
$Format = $_POST["format"];
//$Billede = $_FILES["billede"]["navn"];
//if($_FILES){
// move_uploaded_file($_FILES["billed"]["navn"], $_FILES["billed"]["navn"]);
//}
$user_data = "$Titel, $Hovedskuespiller, $Genre, $Format, $Billede \r\n";
$fh = fopen("data.txt", "a") or die("Fejl i åbning af fil!");
fwrite($fh, $user_data) or die ("Fejl i skrivning til fil!");
fclose($fh);
?>
If i write some HTML in the "eksamen_save_data.php" i can show this, but it wont run the PHP. I'm using XAMPP.
The problem is that it wont save to the "data.txt" file as i tell the PHP to do.
Another question; is there also a way, I can make the PHP run in the same file as where I have my fieldset?
LAST EDIT:
Most of the time it's the little mistakes that proves to be the biggest problem. For me i personally forgot to use: localhost/eksamen_tilføj.php in the browser.
So it was me making a mistake in XAMPP.
Use file_put_contents
file_put_contents("data.txt", $user_data, FILE_APPEND);
It does all the jobs like file open, write and close. Advantage is if the file does not exist then it will create.
Find full working code
<?php
$Titel = $_POST["titel"];
$Hovedskuespiller = $_POST["hovedskuespiller"];
$Genre = $_POST["genre"];
$Format = $_POST["format"];
$Billede = $_FILES["billede"]["name"];
// Example of accessing data for a newly uploaded file
$fileName = $_FILES["billede"]["name"];
$fileTmpLoc = $_FILES["billede"]["tmp_name"];
// Path and file name
$pathAndName = "upload/".$fileName;
// Run the move_uploaded_file() function here
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
// Evaluate the value returned from the function if needed
if ($moveResult == true) {
echo "File has been moved from " . $fileTmpLoc . " to" . $pathAndName;
} else {
echo "ERROR: File not moved correctly";
}
$user_data = "$Titel, $Hovedskuespiller, $Genre, $Format, $Billede \r\n";
file_put_contents("data.txt", $user_data, FILE_APPEND);
?>
you'll have to remove the third parameter $test (because it specifies the length of the content to be written). But $test is not defined in your PHP file, so it won't write anything..
So change this
fwrite($fh, $user_data, $test) or die ("Fejl i skrivning til fil!");
into this
fwrite($fh, $user_data) or die ("Fejl i skrivning til fil!");
and have a look at this :)
As for your second question: sure you can merge your form and submit scripts:
<?php
if(count($_POST) > 0) { //
/** Form submit function, file write **/
} else {
?>
<html>
<form action="#" method="POST">
<!-- Enter HTMLform here -->
</form>
</html>
<?php } ?>
This pseudocode is not pretty, but will do in terms of explaining stuff. The # in the form action means that the same script is to be called upon submission. The if(count($_POST) > 0) checks whether data has been submitted. If so, the file will be written. Otherwise, the form will be displayed.
Good luck.
I want to allow a user to upload multiple text files using a simple HTML form, and then save them to a string. After that, I want to display them to the user. For example, say I have three text files with the following contents:
file1.txt: this is some text.
file2.txt: this is some more text.
file3.txt: even more text!
When the user uploads them using an HTML form, I want to save them to a string and display them like so:
this is some text.
this is some more text.
even more text!
I have the following (incomplete) code that attempts to get only one file:
Upload text documents: <br /><br>
<form action="output.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
<?php
$doc = $_POST['file'];
echo $doc;
?>
How can I loop through the files and save them to a string, then display them in the best way possible?
$filenames = array();
if(isset($_FILES["documents"]))
{
for($i=0; $_FILES['documents']['name'][$i] != '' ; $i++)
{
$filenames[$i] = $_FILES['documents']['name'][$i];
$myfile = fopen("$_FILES['documents']['name'][$i]", "r") or die("Unable to open file!");
echo fread($myfile,filesize("$_FILES['documents']['name'][$i]"));
fclose($myfile);
}
}
I think this is helps for you!!!!!!!1
In completion of White Marcus answer
use the multiple="multiple"attribute in the input file element.
You should have : $_FILES variable, instead of $_POST
<?php
var_dump($_FILES);
?>
To print a file use file_put_contents()
Best regards
$filenames = array();
if(isset($_FILES["documents"]))
{
for($i=0; $_FILES['documents']['name'][$i] != '' ; $i++)
{
$filenames[$i] = $_FILES['documents']['name'][$i];
}
print_r($filename);
}
use the multiple="multiple"attribute in the input file element.
I have a text file in the following format, let's call it stats.txt:
valueA1, valueA2, valueA3, valueA4
valueB1, valueB2, valueB3, valueB4
valueC1, valueC2, valueC3, valueC4
valueD1, valueD2, valueD3, valueD4
I want four text boxes or textareas to populate with this code in an html document and when form is submitted, append to the corresponding lines of the text file. I'm not very knowledgeable with php so can't figure out a way to do this.
My current html file looks like this:
$url = 'editor.php';
$file = 'stats.txt';
// check if form has been submitted
if (isset($_POST['text1']))
{
// save the text contents
file_put_contents($file, $_POST['text1']);
// redirect to form again
header(sprintf('Location: %s', $url));
printf('Updated.', htmlspecialchars($url));
exit();
}
// read the textfile
$text = file_get_contents($file);
?>
I couldn't figure out how to loop between the lines of the text file, so have this chunk of horrible code to get the value of each line:
<?php
//for Line 1
$myLine1 = 1 ;
$linefile1 = new SplFileObject($file);
$linefile1->seek($myLine1-1);
//for Line 2
$myLine2 = 2 ;
$linefile2 = new SplFileObject($file);
$linefile2->seek($myLine2-1);
//for Line 3
$myLine3 = 3 ;
$linefile3 = new SplFileObject($file);
$linefile3->seek($myLine3-1);
//for Line 4
$myLine4 = 4 ;
$linefile4 = new SplFileObject($file);
$linefile4->seek($myLine4-1);
?>
And the form looks like this:
<form action="" method="post">
#stuff 1
<textarea id="stuff" name="stuff[]"><?php echo htmlspecialchars($linefile1) ?></textarea>
#stuff 2
<textarea id="stuff" name="stuff[]"><?php echo htmlspecialchars($linefile2) ?></textarea>
#stuff 3
<textarea id="stuff" name="stuff[]"><?php echo htmlspecialchars($linefile3) ?></textarea>
#stuff 4
<textarea id="stuff" name="stuff[]"><?php echo htmlspecialchars($linefile4) ?></textarea>
<input type="submit" />
<input type="reset" />
</form>
Can someone help me with this please?
Just loop through the lines and display textareas. Using file() to put the file into array
<?php $file = file('stats.txt');?>
<form action="" method="post">
<?php
foreach($file as $line) {
echo "<textarea id='stuff' name='stuff[]'>".htmlspecialchars($line)."</textarea>";
};?>
<input type="submit" />
<input type="reset" />
</form>
Then when you submit the form
if(isset($_POST['stuff'])){
$text = join("\n", $_POST['stuff']);
file_put_contents($file, $text);
};
Here is a code I wrote to store and retrieve data from a text file, that you can use as an example:
// Save Check Boxes in Serial Form for later retrieval
$myFile = "equipment.txt";
if($save == "yes"){
$stringData = serialize(array($container_20,$container_40,$container_45,$container_RF,$container_HQ,$container_Chassis));
file_put_contents($myFile, $stringData);
}
// Read Saved File and Populate Check Boxes
$recoveredData = file_get_contents($myFile);
list($container_20,$container_40,$container_45,$container_RF,$container_HQ,$container_Chassis) = unserialize($recoveredData);