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");
Related
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);
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);
}
I save to file data from form:
$name = $_POST['name'];
$url = $_POST['url'];
$comm = $_POST['comm'];
$data["name"]=$name;
$data["url"]=$url;
$data["comm"]=$comm;
file_put_contents("db.txt", serialize($data));
Now, I would like to read this file record by record.
$file_handle = fopen("db.txt", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
$arr = unserialize($line);
var_dump($arr);
}
fclose($file_handle);
But this code read only last record. How to read all file?
Replace file_put_contents("db.txt", serialize($data)); to
file_put_contents("db.txt", PHP_EOL .serialize($data), FILE_APPEND);
file_put_contents("db.txt", serialize($data));// will over write the file again and again. so you cant able to read all the data. FILE_APPEND helps to append the data And PHP_EOL helps to leave a line breake.
Hi i try this code for your solution:
<?php
$name = "rdn";
$url = "http://google.it";
$comm = "com";
$data["name"]=$name;
$data["url"]=$url;
$data["comm"]=$comm;
file_put_contents("db.txt", serialize($data)."\n",FILE_APPEND);
$fh = fopen('db.txt','r');
while ($line = fgets($fh)) {
// <... Do your work with the line ...>
var_dump(unserialize($line));
}
fclose($fh);
?>
without "\n" don't work!
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.
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);
?>