Write in a .txt File from a form in PHP - php

I saw this question and I wanted to ask a question in the comment but didn't have enough reputation. So I'm asking the question here.
I have a form in HTML:
<form action="myprocessingscript.php" method="POST">
Name : <input name="field1" type="text" />
Email : <input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
And a processing script in php, myprocessingscript.php :
if (isset($_POST['field1']) && isset($_POST['field2'])) {
$data = 'comments.txt' . $_POST['field1'] . ' ' . $_POST['field2'] . "\n";
$ret = file_put_contents('comments.txt', $data);
if ($ret === false) {
die('There was an error Sending The Comment');
}
else {
echo "The Comment Has Been Sent Succesfully !";
}
}
else {
die('Fill in The Form Please !');
}
if (isset($_POST['field1']) && isset($_POST['field2'])) {
$data = 'comments.txt' . $_POST['field1'] . ' ' . $_POST['field2'] . "\n";
$ret = file_put_contents('comments.txt', $data);
if ($ret === false) {
die('There was an error Sending The Comment');
}
else {
echo "The Comment Has Been Sent Succesfully !";
}
}
else {
die('no post data to process');
}
When I write something in the form to a text file (comments.txt) the previous text is deleted - what should I do?

You just need to add the 'append' flag to file_put_contents() :
file_put_contents('comments.txt', $data, FILE_APPEND);
See : http://uk3.php.net/manual/en/function.file-put-contents.php

Related

php Activating On Page Load While Inside Of onsubmit

I have a php function to create a file in a directory on submission of a form.
The code is:
<form id="myForm" onSubmit="<?php
error_reporting(E_ALL);
$directory = __DIR__ . "/images/"; $filecount = 0; $files = glob($directory . "*"); if ($files){
$filecount = count($files); }
$filecount = $filecount + 1;
$pagename = 'image_'.$filecount;
$newFileName = './images/'.$pagename;
$newFileContent = 'Page Content';
if (file_put_contents($newFileName, $newFileContent) !== false) {
echo "File created (" . basename($newFileName) . ")";
} else {
echo "Cannot create file (" . basename($newFileName) . ")";
}
?>">
<input placeholder="Username 0/25" name="user" id="user" maxlength="25" required>
<input placeholder="Password 0/45" name="password" id="password" maxlength="45" required>
<input placeholder="Image Name" name="name" id="name">
<input type="file" placeholder="Image" accept="image/*" name="img" required>
<button type="submit">Upload</button>
</form>
The problem is that it auto activates on page load.. is there a way to fix that
The problem is that it auto activates on page load
to prevent auto loading the page when you press on submit, you could use this trick "return false; \"..." but it doesn't create the image file :/ just stop the page from action.
if (file_put_contents($newFileName, $newFileContent) !== false) {
echo "return false; \"File created (" . basename($newFileName) . ")";
} else {
echo "return false; \" Cannot create file (" . basename($newFileName) . ")";
}
I try to imitate you're project, however i used txt files instead of images.
I used AJAX
index.html
<html>
<body>
<form id="myForm">
<button type="submit">create a file</button>
</form>
<script src="script.js"></script>
</body>
</html>
script.js
document.getElementById('myForm').onsubmit = function(e){
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open('GET','creating.php');
xhr.onreadystatechange = function(){
console.log(xhr.readyState)
if(xhr.readyState == XMLHttpRequest.DONE)
if(xhr.response.startsWith('Woow'))
alert('File created successfully!');
else
alert('Something went wrong!');
}
xhr.send();
}
creating.php
<?php
$directory = __DIR__ . "/files/";
$filecount = count(glob($directory . "*")) + 1;
$newFileName = $directory.'txt_'.$filecount.'.txt';
$newFileContent = "some text... in a file number $filecount.";
if(file_put_contents($newFileName, $newFileContent))
echo "Woow!";
else
echo "Oups!";
?>

How to add href link with multiple php values?

I have little problem with php web form for add link.
I want the form to record the values in:
.$_POST['field2']
But I don't know how to do it to work correctly.
My code is...
HTML form code:
<form action="myprocessingscript.php" method="POST">
<p>Уеб Сайт: </p><input name="field1" type="text" placeholder="https://www.tvoiasait.com/" /><br />
<p>Ключова дума: </p><input name="field2" type="text" placeholder="Моят Личен Блог" /><br />
<p>Описание: </p><input name="field3" type="text" placeholder="Личен Блог за интересни неща" /><br />
<br /><input type="submit" name="submit" value="Добави сайта">
</form>
myprocessingscript.php code is:
<?php
if(isset($_POST['field1']) && isset($_POST['field2']) && isset($_POST['field3'])) {
$data = '<a href='.$_POST["field1"]' target='_blank' rel='nofollow' title='.$_POST["field3"]'>.$_POST["field2"]</a>' . "\n";
$ret = file_put_contents('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');
}
?>
and my code for show form records is:
<?php
$myfile = fopen("mydata.txt", "r") or die("Unable to open file!");
while(!feof($myfile)) {
echo fgets($myfile);
}
fclose($myfile);
?>
I want to use this form on my website so that visitors can add their link to them. I don't understand how to use $_POST['field1'] in HTML row.
Thanks for your time and attention.
<?php echo $_POST['field2'] ?>
or
<?php
echo '<a href="' . $_POST['field1'] . '" target="_blank" rel="nofollow"
title="' . $_POST['field3'] . '"><' . $_POST['field2'] . '</a>':
?>
This below "" string addition could solve your problem.
<?php
if(isset($_POST['field1']) && isset($_POST['field2']) && isset($_POST['field3'])) {
$data = ''.$_POST["field2"].'' . "\n";
$ret = file_put_contents('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');
}
?>

html form to txt with php

idk why but its just dont work for me..
this is in index.html
<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>
in myprocessingscript.php
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] ."\n";
$ret = file_put_contents('log.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');
}
?>
log.txt exist..
any one have an idea ?

Loading file to server

I have two forms on one page that should give users posibility to load file to server(from URL or from user's PC)
<form method="post" action="bigorder.php" name="photourl">
<label for="photoorig">URL</label>
<input type="url" name="photoorig" placeholder="">
<input type="submit" value="Load" name="photoload">
<br>
</form>
<form method="post" action="bigorder.php" name="photofile" enctype="multipart/form-data">
<label for="photoloc">Load own file</label>
<input type="file" name="photoloc" id="photoloc">
<input type="submit" value="Load" name="photoload2">
</form>
And php
<?php
$tmpname=rand().".jpg";
if ($_POST['photoorig']) {
$file=file_get_contents($_POST['photoorig']);
$fp = fopen("/var/www/html/uploads/tmp/".$tmpname, "w");
fwrite($fp, $file);
fclose($fp);
}
if ($_POST['photoloc']) {
$tmpFile = $_FILES['photoloc']['tmp_name'];
$newFile = "/var/www/html/uploads/tmp/".$_FILES['photoloc']['name'];
$result = move_upload_file($tmpFile, $newFile);
echo $_FILES['photoloc']['name'];
if ($result) {
echo ' was uploaded<br />';
} else {
echo ' failed to upload<br />';
}
?>
First form loads files fine, but the second one doesn't work at all. I even don't receive any error message.
What am I doing wrong? Or missing something?
Here is the correct code,it is working.In your code curly braces was missing in second form and isset() function should use to check posted data set or not.
<?php
$tmpname=rand().".jpg";
if (isset($_POST['photoload'])) {
echo '1st';
$file=file_get_contents($_POST['photoorig']);
$fp = fopen("/var/www/html/uploads/tmp/".$tmpname, "w");
fwrite($fp, $file);
fclose($fp);
}
if (isset($_POST['photoload2'])) {
echo '2nd';
$tmpFile = $_FILES['photoloc']['tmp_name'];
$newFile = "/var/www/html/uploads/tmp/".$_FILES['photoloc']['name'];
$result = move_upload_file($tmpFile, $newFile);
echo $_FILES['photoloc']['name'];
if ($result) {
echo ' was uploaded<br />';
} else {
echo ' failed to upload<br />';
}
}
?>

Create variable that generates unique txt file then appends without creating another text file

I have a form that on submit creates a unique .txt filename and posts form data into that file. That works well. The issue is after it creates the file, I need a way to append it without creating another text file. Because it is a form, when it submits, the code reruns each time submit is called and I'm not sure how to handle it.
Here is the form:
<body>
<form action="write_to_txt_file2.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
Here is the php:
I don't have to use the microtime as the unique variable name so if there is a better way, I'm open to changing it.
<?php
$myDate = round(10*microtime(TRUE));
$filename = "tmp/".$myDate.".txt";
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents($filename, $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');
}
?>
Alternatively, you could utilize sessions also to this, set the filename if not set using that same generator, so that you could use it again after the next submissions.
Simple example:
session_start();
if(!isset($_SESSION['file'])) {
$_SESSION['file'] = round(10*microtime(TRUE)); // set a filename on initial load
}
if(isset($_POST['submit'])) { // if submitted
$myDate = $_SESSION['file'];
$filename = "tmp/".$myDate.".txt";
if(isset($_POST['field1'], $_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents($filename, $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');
}
}
if(isset($_POST['create'])) {
$_SESSION['file'] = round(10*microtime(TRUE)); // creates another filename
}
?>
<form action="" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data" />
<input type="submit" name="create" value="Create New" />
</form>

Categories