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);
Related
I'm a begginer in PHP and I want to get data from a form which contains a name,a comment and a name of a photo the user selects, and put it in a csv.But when i try to write the date, the data i already have in the csv is overwrited.So every time I only have one line in my csv with the newest data.
I want data to be introduced in a new csv line everytime the form is used like this:
Russel,Hello,Football.jpg
James,Bye,Coke.png
Instead of being overwrited like this:
James,Bye,Coke,png
This is what i tried:
if (isset($_POST['submit'])) {
$name = $_POST["nom"];
$comment = $_POST['com'];
$image = $_FILES['imag']['name'];
$csvfile = 'fichero.csv';
$fvisitas = fopen($csvfile, "c+");
$lista = array(
array($name, $comment, $image)
);
foreach ($lista as $campos) {
fputcsv($fvisitas, $campos);
}
fclose($fvisitas);
}
You should open your file with the append flag
$fvisitas = fopen($csvfile, "a");
This will let you append lines instead.
You should use a+ mode.
For more about fopen modes refer to fopen
$fvisitas = fopen($csvfile, "a+");
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!
Updated Situation:
I have managed to create a registration form that outputs the data to a new CSV file for use into a separate database. However the code that sends the attachment doesn't work, but the system stores the file into a separate folder (I must stress this is while I am testing).
My question is, can I both create the CSV file and send it via email? If so, what do I need to do?
I am also aware that there are security risks: One suggestion has been to store the CSV files outside to root directory. is this foolproof and if not, could anyone make any recommendations?
My code is:
<?php
$_POST['password'] = md5($_POST['password']);
$headers=array_keys($_POST);
$file = "csv/" . $_POST['username'].date('Ymdhis').".csv"; //filename
$file = fopen($file, 'a');
fputcsv($file, $headers);
fputcsv($file, $_POST);
fclose($file);
require_once('email/PHPMailerAutoload.php');
$m = new PHPMailer;
$m->isSMTP();
$m->SMTPAuth = true;
$m->SMTPDebug = 0;
$m->Host = 'mymail.com';
$m->Username = 'me#mymail.com';
$m->Password = 'mypass';
$m->SMTPSecure = 'SSL';
$m->Port = 26;
$m->From = 'me#mymail.com';
$m->FromName = 'My name';
$m->addReplyTo('me#mymail.com', 'Reply Address');
$m->AddAddress('me#mymail.com', 'My name');
$m->isHTML(true);
$m->addAttachment('csv/data.csv', 'data.csv');
$m->Subject = 'New feed ';
$m->Body = '<p>This is an email just sent from our website</p><p><strong>Please import into your database.</strong></p>';
$m->AltBody = 'This is the body. Please import into the database';
if($m->send()) {
echo '<h1>Thank you</h1> <p>We have received your Registration and will send you confirmation details shortly.</p>';
} else {
echo $m->ErrorInfo;
}
I also have a checkbox field that needs to be written with the commas separating the values, for example 1,2,3. How can I write this?
Any assistance/advice will as always be gratefully received.
Many thanks in advance.
$_POST['id']="101"; //example data
$_POST['username']="kraysak"; //example data
$_POST['password']="grumpycat"; //example data
$_POST['usergroup']="admin"; //example data
$_POST['lastaccess']="14-10-2014 00:01"; //example data,
$_POST['password'] = md5($_POST['password']);
$headers=array_keys($_POST);
$file = $_POST['username'].date('Ymdhis').".csv"; //filename
$file = fopen($file, 'a');
fputcsv($file, $headers ); //write headers (key of the $_POST array (id,username,password,etc)
fputcsv($file, $_POST );
fclose($file);
this create a file named kraysak20141014010253.csv with the next information:
id,username,password,usergroup,lastaccess
101,kraysak,5557981401e83c1963412f19c7487965,amdin,"14-10-2014 00:01"
is hard for me to explain, (my english isn't good enought) but fputcsv funtion write the content of an array in the file, and $_POST is an array... so, you dont need to create new variables, you only need to use md5() function in one variable.
fputcsv consists of two parameters; location and content. So;
fputcsv(location, content);
or
$fileNameVariable = 'blah';
$fileName = $fileNameVariable . date('Ymdhis') . '.csv';
$fp = fopen('/exampleDirectoryName/' . $fileName, 'w');
$headers = array ('info1', 'info2', 'info3');
fputcsv($fp, $headers);
You can adapt this exmaple for your situation pretty easily.
Try:
$csvname=md5(rand());
$fp = fopen("csv/$csvname.csv", "w");
$savearray = [ $name, $email, $password, $usergroup, $lastsid, $fname, $lname, $lastaccess, $company, $phone, $addone, $addtwo, $city, $stateprov, $country, $postalcode, $rescom, $addbook, $subscriptions, $affilid, $affilcommpct, $affilsalestodate, $affilcommearned, $affilcommowed, $affilcommpaid, $whlsalepct, $show_currency, $loyaltypoints ];
fputcsv($fp, $savearray);
fclose($fp);
Use array() on $savearray instead of [] for older php versions.
So I have a JSON file containing basketball player information in the following format:
[{"name":"Lamar Patterson","team":1,"yearsLeft":0,"position":"PG","PPG":17},{"name":"Talib Zanna", "team":1,"yearsLeft":0,"position":"SF","PPG":13.1},....]
I want a user to be a able to add their own custom players to this file. To do this i try the following:
<?php
$json = file_get_contents('json/players.json');
$info = json_decode($json, true);
$info[] = array('name'=>$name, 'team'=>$team, 'yearsLeft'=>4, 'position'=>$position, 'PPG'=>$ppg);
file_put_contents('json/players.json', json_encode($info));
?>
This "sort of" works. But when I check the JSON file, I find that there are 3 new entries rather than 1:
{"name":"","team":null,"yearsLeft":4,"position":"","PPG":""},{"name":"","team":"3","yearsLeft":4,"position":"","PPG":""},{"name":"Jeff","team":null,"yearsLeft":4,"position":"C","PPG":"23"}
assuming $name="Jeff" $team=3 and $ppg=23 (populated via POST submission).
What's going on and how can I fix it?
You could try doing the following:
Untested code
<?php
if(!empty($name) && !empty($team) && !empty($position) && !empty($ppg)) {
$fh = fopen('json/players.json', 'r+') or die("can't open file");
$stat = fstat($fh);
ftruncate($fh, $stat['size']-1);//removes last ] char
fclose($fh);
$fh = fopen('json/players.json', 'a');
$info = array('name'=>$name, 'team'=>$team, 'yearsLeft'=>4, 'position'=>$position, 'PPG'=>$ppg);
fwrite($fh, ','.json_encode($info).']');
fclose($fh);
}
?>
This will append the only the new json to the file instead of opening the file, making php parse all the json and then writing it to the file again. In addition to that it will only store the data if the variables actually contain data.
Try this:
<?php
//get the posted values
$name = $_POST['name'];
$team = $_POST['team'];
$position = $_POST['position'];
$ppg = $_POST['ppg'];
//verify they're not empty
if(!empty($name) && !empty($team) && !empty($position) && !empty($ppg)) {
//Open the file
$fh = fopen('json/players.json', 'r+') or die("can't open file");
//get file info/stats
$stat = fstat($fh);
//final desired size after trimming the trailing ']'
$size = $stat['size']-1;
//file has contents? then remove the trailing ']'
if($size>0) ftruncate($fh, $size);
//close the current handle
fclose($fh);
// reopen the file for append
$fh = fopen('json/players.json', 'a');
//build your data array
$info = array('name'=>$name, 'team'=>$team, 'yearsLeft'=>4, 'position'=>$position, 'PPG'=>$ppg);
//if this is not the first item on file
if($size>0) fwrite($fh, ','.json_encode($info).']'); //append with comma
else fwrite($fh, '['.json_encode($info).']'); //first item on file
fclose($fh);
}
?>
Maybe your php config is not set to convert the post/get variables to global variables. This happened to me a couple of times so I rather create the variables I'm expecting from the post/get request. Also watch out for the page encoding, from personal experience you could be getting empty strings there.
I tried and looked for a solution, but cannot find any definitive.
Basically, I have a txt file that lists usernames and passwords. I want to be able to change the password of a certain user.
Contents of users.txt file:
user1,pass1
user2,pass2
user3,pass3
I've tried the following php code:
// $username = look for this user (no help required)
// $userpwd = new password to be set
$myFile = "./users.txt";
$fh = fopen($myFile,'r+');
while(!feof($fh)) {
$users = explode(',',fgets($fh));
if ($users[0] == $username) {
$users[1]=$userpwd;
fwrite($fh,"$users[0],$users[1]");
}
}
fclose($fh);
This should works! :)
$file = "./users.txt";
$fh = fopen($file,'r+');
// string to put username and passwords
$users = '';
while(!feof($fh)) {
$user = explode(',',fgets($fh));
// take-off old "\r\n"
$username = trim($user[0]);
$password = trim($user[1]);
// check for empty indexes
if (!empty($username) AND !empty($password)) {
if ($username == 'mahdi') {
$password = 'okay';
}
$users .= $username . ',' . $password;
$users .= "\r\n";
}
}
// using file_put_contents() instead of fwrite()
file_put_contents('./users.txt', $users);
fclose($fh);
I think when you get that file use file_get_contents after that use preg_replace for the particular user name
I have done this in the past some thing like here
$str = "";
$reorder_file = FILE_PATH;
$filecheck = isFileExists($reorder_file);
if($filecheck != "")
{
$reorder_file = $filecheck;
}
else
{
errorLog("$reorder_file :".FILE_NOT_FOUND);
$error = true;
$reorder_file = "";
}
if($reorder_file!= "")
{
$wishlistbuttonhtml="YOUR PASSWORD WHICH YOU WANT TO REPLACE"
$somecontent = $wishlistbuttonhtml;
$Handle = fopen($reorder_file, 'c+');
$bodytag = file_get_contents($reorder_file);
$str=$bodytag;
$pattern = '/(YOUR_REGEX_WILL_GO_HERE_FOR_REPLACING_PWD)/i';
$replacement = $somecontent;
$content = preg_replace($pattern, $replacement, $str,-1, $count);
fwrite($Handle, $content);
fclose($Handle);
}
Hope this helps....
The proper way of doing this is to use a database instead. Databases can do random access easily, doing it with text files less so.
If you can't switch to a database for whatever reason, and you don't expect to have more than about a thousand users for your system, then it would be far simpler to just read the whole file in, convert it to a PHP data structure, make the changes you need to make, convert it back into text and overwrite the original file.
In this case, that would mean file() to load the text file into an array with each element being a username and password as a string, explode all elements on the array at the comma to get the username and password separately, make the changes you need to make, then write the modified data to disc.
You might also find fgetcsv() useful for reading the data. If you SplFileObject and have a recent version of PHP then fputcsv() may also be available to write the data back out.
However, just using a database is a far better solution. Right tool for the job.
$fn = fopen("test.txt","r") or die("fail to open file");
$fp = fopen('output.txt', 'w') or die('fail to open output file');
while($row = fgets($fn))
{
$num = explode("++", $row);
$name = $num[1];
$sex = $num[2];
$blood = $num[3];
$city = $num[4];
fwrite($fp, "Name: $name\n");
fwrite($fp, "Sex: $sex\n");
fwrite($fp, "Blood: $blood\n");
fwrite($fp, "City: $city\n");
}
fclose($fn);
fclose($fp);
If you're on a *nix system you could use sed; I find it neater than playing with file handles etc:
exec("sed -i '/^$username,.\+\$/$username,$userpwd/g' ./users.txt 2>&1", $output, $return);
If not I'd agree with GordonM and parse the file into a PHP data structure, manipulate it, then put it back:
$data = file_get_contents('./users.txt');
$users = array_map(function($line) {
return explode(',', $line);
}, explode("\n", $data));
foreach ( $users as $i => $user ) {
if ( $user[0] == $username ) {
$user[1] = $userpwd;
$users[$i] = $user;
}
}
file_put_contents('./users.txt', implode("\n", array_map(function($line) {
return implode(',', $line);
}, $users)));
There are, of course, an infinite number of ways of doing that!