Php input data ontop of txt file - php

I want to Add new data at the starting of my text file. Dats is coming dynamically.
Below is the code i have try so far :
if(isset($_POST["posten"])){
$naam = $_POST['naam']."ø";
$achternaam = $_POST['achternaam']."ø";
$email = $_POST['email']."ø";
$bericht = $_POST['bericht']."\n";
$infile = fopen("berichten.txt","a");
if (flock($infile,LOCK_EX)){
fwrite($infile, $naam);
fwrite($infile, $achternaam);
fwrite($infile, $email);
fwrite($infile, $bericht);
flock($infile,LOCK_UN);
}
fclose($infile);
}

this works for me
if(isset($_POST["posten"])){
$naam = $_POST['naam']."ø";
$achternaam = $_POST['achternaam']."ø";
$email = $_POST['email']."ø";
$bericht = $_POST['bericht']."\n";
$file_data = "$naam"."$achternaam"."$email"."$bericht";
$file_data .= file_get_contents('berichten.txt');
file_put_contents('berichten.txt', $file_data);
}

Related

Need help writing and reading a file with PHP

So for an assignment, I have to create a form where users can post ride shares so other people can see and join their ride. I'm doing this by writing the form to a file data.txt, and reading the file to display all the rides on a board. My only problem is when I get the contents of data.txt, it's all combined together. I need to be able to display each ride separately. How would I go about doing this?
Here is my code so far:
The writing:
if (isset($_POST['name'])
&& isset($_POST['email'])
&& isset($_POST['date'])
&& isset($_POST['destination'])
&& isset($_POST['msg'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$date = $_POST['date'];
$destination = $_POST['destination'];
$msg = $_POST['msg'];
//TODO the file write here VV, use 'a' instead of 'w' too ADD to the file instead of REWRITING IT.
$arr = [$name,$email,$date,$destination,$msg];
$write = json_encode($arr);
$file = fopen('data.txt', 'a');
fwrite($file, $write);
fclose($file);
}
And the reading:
$path = 'data.txt';
$handle = fopen($path, 'r');
$contents = fread($handle, filesize($path));
echo $contents;
fclose($handle);
$newarr = [json_decode($contents)];
foreach($newarr as $stuff)
{
echo $stuff[0];
}
And the output is something like:
["Simon Long","example#gmail.com","2109-01-01T01:01","canada","this is a message"] Simon Long
Let's say there are multiple postings in there, it would just print them all together. I need a way to separate postings so I can display them nicely on the board.
Use a multidimensional array.
$arr = [
"Simon Long","example#gmail.com","2109-01-01T01:01","canada","this is a message",
"John Doe","john#gmail.com","2109-01-01T01:01","canada","this is a message",
"Jane Doe","jane#gmail.com","2109-01-01T01:01","canada","this is a message"
];
Then you when you add to it just append to the final array and replace the whole file.
$contents = file_get_contents($path);
$decoded = json_decode($contents);
$decoded[] = [$name,$email,$date,$destination,$msg];
file_put_contents($path, json_encode($decoded)); //replace the entire file.
Also just as a side note. isset accepts multiple arguments so you don't need to use it as you are. You can do this:
if (isset($_POST['name'], $_POST['email'], $_POST['date'], $_POST['destination'] ...)
It's also a good idea to sanitise any input from the user.
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);

How to I create a new file with php Post Data

I am working on this website(for minecraft servers) that when you enter in a few things about your server, it will upload the info onto the list of servers. The thing is, I am a complete noob at PhP.
Here is my form code:
http://pastie.org/8061636
And here is my php code:
<?php
$name = $_POST['sName'];
$ip = $_POST['sIp'];
$port = $_POST['sPort'];
$desc = $_POST['sDesc'];
$finalName = $ip."(".$port.").txt";
$file = fopen($finalName, "w");
$size = filesize($finalName);
if($_POST['submit']) fwrite($file, "$name, $ip, $port, $desc");
header( 'Location: http://www.maytagaclasvegas.com/uniqueminecraftservers/upload/' ) ;
?>
Now what I am trying to do it get do is create a new file name using $ip and $port, and put this into a table. Can anyone help a newbie out? Thanks
Try something like this
file_put_contents("/path/to/files/".$ip."-".$port.".dat",
$_POST['sName'].",".$_POST['sIp'].",".$_POST['sPort'].",".
$_POST['sDesc']);
Then to create your table you would need to do something like this.
$files = glob("/path/to/files/*.dat");
echo "<table>";
foreach($files as $file){
echo "<tr><td>".implode("</td><td>", explode(",",file_get_contents($file),4))."</td></tr>";
}
echo "</table>";
It would be a lot safer though to just use a database.
Try this one:
<?php
$name = $_POST['sName'];
$ip = $_POST['sIp'];
$port = $_POST['sPort'];
$desc = $_POST['sDesc'];
$finalName = $ip."(".$port.").txt";
if($_POST['submit']) {
$file = $finalName;
// Append a new person to the file
$content = "$name, $ip, $port, $desc";
// Write the contents back to the file
file_put_contents($file, $current);
}
?>
Note: Be sure you have write (may be 777 in linux) permission on your folder where you are saving the file.

Creating XML file from HTML form

Ok so I got it working, now the only problem is when a new submission is added it overwrites the previous entry. I need it to add the newest submission to the XML file and not over ride it and store it for X amount of time.
Here is the working php script that creates the xml file and takes the data from the HTML form and puts it in the XML file.
<?php
if (isset($_POST['lsr-submit']))
{
header('Location: http://www.mesquiteweather.net/wxmesqLSR.php');
}
$str = '<?xml version="1.0" encoding="UTF-8"?><entrys></entrys>';
$xml = simplexml_load_string($str);
$fname = $_POST['firstname'];
$lname = $_POST['lastname'];
$location = $_POST['location'];
$report = $_POST['report'];
$description = $_POST['desc'];
$fname = htmlentities($fname, ENT_COMPAT, 'UTF-8', false);
$lname = htmlentities($lname, ENT_COMPAT, 'UTF-8', false);
$location = htmlentities($location, ENT_COMPAT, 'UTF-8', false);
$report = htmlentities($report, ENT_COMPAT, 'UTF-8', false);
$description = htmlentities($description, ENT_COMPAT, 'UTF-8', false);
$xml->reports = "";
$xml->reports->addChild('fname', $fname);
$xml->reports->addChild('lname', $lname);
$xml->reports->addChild('location', $location);
$xml->reports->addChild('report', $report);
$xml->reports->addChild('description', $description);
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$doc->preserveWhiteSpace = true;
$doc->loadXML($xml->asXML(), LIBXML_NOBLANKS);
$doc->save('test2.xml');
?>
Here is the xml file it creates.
XML FILE
Here is the form to submit to the XML file. Submit a test submission and it takes you to the page to display but you'll notice it will overwrite the last one instead of adding to the XML file.
HTML FORM
This is what I came up with and works well, and tested.
NOTE: However if the file (file.xml) does not exist, it will throw off an error, so if you figure out a way to automatically delete the old file(s) via CRON or any other method (you mentioned: "...and store it for X amount of time."), you'll have to come up with a way to make a pre-built structured file with at least one set of entries inside it.
E.g.:
<?xml version="1.0" encoding="UTF-8"?>
<entries>
<reports>
<timestamp>May 31, 2013, 11:56 am</timestamp>
<fname>Fred</fname>
<lname>Fletcher</lname>
<location>Canada</location>
<report>Wind Damage</report>
<description>Winds were gusting mighty hard today!</description>
</reports>
</entries>
This is relatively easy to do, I've done it before with an if file exists....
Here is my working code:
<?php
// Script by Fred Fletcher, Canada.
$fname = $_POST['firstname'];
$lname = $_POST['lastname'];
$location = $_POST['location'];
$report = $_POST['report'];
$description = $_POST['desc'];
$xml = new DOMDocument('1.0', 'utf-8');
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->load('file.xml');
$element = $xml->getElementsByTagName('reports')->item(0);
$timestamp = $element->getElementsByTagName('timestamp')->item(0);
$fname = $element->getElementsByTagName('fname')->item(0);
$lname = $element->getElementsByTagName('lname')->item(0);
$location = $element->getElementsByTagName('location')->item(0);
$report = $element->getElementsByTagName('report')->item(0);
$description = $element->getElementsByTagName('description')->item(0);
$newItem = $xml->createElement('reports');
$newItem->appendChild($xml->createElement('timestamp', date("F j, Y, g:i a",time())));;
$newItem->appendChild($xml->createElement('fname', $_POST['firstname']));
$newItem->appendChild($xml->createElement('lname', $_POST['lastname']));
$newItem->appendChild($xml->createElement('location', $_POST['location']));
$newItem->appendChild($xml->createElement('report', $_POST['report']));
$newItem->appendChild($xml->createElement('description', $_POST['desc']));
$xml->getElementsByTagName('entries')->item(0)->appendChild($newItem);
$xml->save('file.xml');
echo "Data has been written.";
?>
A "plug" as a comment in the script would be nice, "Script by Fred Fletcher, Canada." (wink)
Let me know how this works out for you.
I am not sure I got your question, but if you need to create a file that is unique for each submission then you cannot simply use echo, you must actually create a file.
Also if after submitting you redirect to another PHP file, how can you handle the data to write into the variables?
Example for creating a file:
<?php // testfile.php
$fh = fopen("testfile.xml", 'w') or die("Failed to create file");
$text = <<<_END
Line 1
Line 2
Line 3
_END;
fwrite($fh, $text) or die("Could not write to file");
fclose($fh);
?>

how to customize text name on php when using fopen comman

how can i customize the text name for the output on my fopen?
i tried using
$file = $Aname .'.txt';
but it won't output correctly, and also after creating the text file return to the page
and prompt the user regarding the creation of the file .
<?php
$saving = $_REQUEST['saving'];
if ($saving == 1){
$Aname = $_POST['Aname'];
$name = $_POST['name'];
$last = $_POST['last'];
$mob = $_POST['mob'];
$ext = $_POST['ext'];
$email = $_POST['email'];
$add = $_POST['add'];
$com = $_POST['com'];
$day = $_POST['day'];
$text = $_POST['text'];
$date = date("M j, Y ");
$data = "Date Sent: {$date}\n\nName: {$name} {$last}\nPhone : {$mob} ext: {$ext}\nCompany: {$com}\nAddress : {$add}\nE-mail : {$email}\nDay : {$day}\n\nNote :
\n{$text}\n---------------------------------------\n";
$file = $Aname.'.txt';
$fp = fopen($file, "a") or die("Couldn't open $file for writing!");
fwrite($fp, $data) or die("Couldn't write values to file!");
fclose($fp);
}
?>
and also instead of relocating the user to another page to give this error
die("Couldn't write values to file!");
just pop up an alert on the page.
Make sure that $_POST['Aname'] is actually populated (maybe it is coming from $_GET?).
Do note by the way that you have opened a rather big security issue here by using unsanitized data to write to disk. Potentially people could overwrite any file on your disk with PHP code and then execute that.
Try using file_put_contents(). It replaces the whole fopen, fwrite, fclose headache.
http://php.net/manual/en/function.file-put-contents.php
<?php
$saving = $_REQUEST['saving'];
if ($saving == 1){
$Aname = $_POST['Aname'];
$name = $_POST['name'];
$last = $_POST['last'];
$mob = $_POST['mob'];
$ext = $_POST['ext'];
$email = $_POST['email'];
$add = $_POST['add'];
$com = $_POST['com'];
$day = $_POST['day'];
$text = $_POST['text'];
$date = date("M j, Y ");
$data = "Date Sent: {$date}\n\nName: {$name} {$last}\nPhone : {$mob} ext: {$ext}\nCompany: {$com}\nAddress : {$add}\nE-mail : {$email}\nDay : {$day}\n\nNote :
\n{$text}\n---------------------------------------\n";
$file = $Aname.'.txt';
file_put_contents ( $file, $data );
}
?>
You should use an absolute path for the $filename parameter of fopen, so replace your following line:
$file = $Aname.'.txt';
for this one:
$file = dirname($_SERVER["SCRIPT_FILENAME"]) . '/' . $Aname.'.txt';
The above assumes your web server runs linux, if it's a windows one, you have to escape any backslashes, like fopen("c:\\my\\document_root\\myfile.txt", "a");

Help writing to two files simultaneously in PHP?

In the script below, I try to write in the same time in two files, but don't perform. How I can do it ?
$filename1 = "guestbook.doc" ;
$filename2 = "cour.doc" ;
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = stripslashes(nl2br(htmlentities($_POST['message'])));
$d = date ( "d/m/Y H:i:s" )
$handle1 = fopen($filename1, "w+");
$handle2 = fopen($filename2, "a+");
if ($handle1 && $handle2) {
fwrite($handle1, "<b>$name</b> "." - $d<br>$message<br><hr>\n");
fwrite($handle2, "<b>$name</b> ".$email." - $d<br>$message<br>\n");
}
if ($handle1) {
fclose($handle1);
}
if ($handle2) {
fclose($handle2);
}
then
{
header('Location: contact.php?' . http_build_query($_POST));
}
?>
One thing I do notice is that is kinda odd is :
then
{
header('Location: contact.php?' . http_build_query($_POST));
}
then is not a valid control structure. It's if/elseif/else.
writing to a file in PHP is procedural it will wait for handle1 to be written before moving onto handle2. It will not write them at the same time. There must be an error occurring or its not getting inside the if statement if($handle1 && $handle2) . It possibly cannot open those files for writing due to permission problems? are there any errors at all?
Try replacing that if statement with something like this and see if it breaks?
if (is_writable($filename1) or die ("Can not write to ".$filename1)) {
fwrite($handle1, "<b>$name</b> "." - $d<br>$message<br><hr>\n");
}
if (is_writable($filename2) or die ("Can not write to ".$filename2)) {
fwrite($handle2, "<b>$name</b> "." - $d<br>$message<br><hr>\n");
}
Just write one under another it will work perfect.
<?php
$filename = "guestbook.doc" ;
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = stripslashes(nl2br(htmlentities($_POST['message'])));
$d = date ( "d/m/Y H:i:s" )
$handle1 = fopen($filename, "w+");
$size = filesize($filename);
fwrite($handle, "<b>$name</b> "." - $d<br>$message<br><hr>\n");
$text = fread($handle, $size);
fclose($handle);
$filename = "cour.doc" ;
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = stripslashes(nl2br(htmlentities($_POST['message'])));
$d = date ( "d/m/Y H:i:s" )
$handle = fopen($filename1, "w+");
$size = filesize($filename1);
fwrite($handle, "<b>$name</b> ".$email." - $d<br>$message<br>\n");
$text = fread($handle, $size);
fclose($handle);
?>

Categories