I'm wanting to store basic data from a single form box and I've created this php code base, but it doesn't seem to be working. Can someone take a glance and see if anything stands out to why this wouldn't work.
Edit: the csv file never updates with new data
if (isset($_POST["submit"]))
{
$name = $_POST["name"];
date_default_timezone_set('America/New_York');
$date = date('Y-m-d H:i:s');
if (empty($name))
{
echo "ERROR MESSAGE";
die;
}
$cvsData ='"$name","$date"'.PHP_EOL;
$cvsData .= "\"$name\",\"$date\"".PHP_EOL;
$fp = fopen("emailAddressses.csv", "a");
if ($fp)
{
fwrite($fp,$cvsData); // Write information to the file
fclose($fp); // Close the file
}
}
Use the nicer way in php : fputcsv
Otherwise you need to do lot of error handling to achieve in your case.
$list = array (
array('First Name', 'Last Name', 'Age'),
array('Angelina ', 'Jolie', '37'),
array('Tom', 'Cruise', '50')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
You should look into fputcsv. This will add CSV to you file and take care of fields and line ends.
fputcsv($fp,array(array($name,$date)));
You can also specify delimiters and such if you want.
This part will not behave like you expect, the variables are not evaluated when inside single quotes:
$cvsData ='"$name","$date"'.PHP_EOL;
You will need to use double quotes:
$cvsData ="\"$name\",\"$date\"".PHP_EOL;
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 am new to both PHP and understanding GET/POST. I am using a postbackurl to this phpfile and trying to write GET/POST information to a text file. It's not working and I was hoping someone could point out my likely obvious error to me. Below is the code.
$postback_data = $_REQUEST;
foreach($postback_data as $key=>$var)
{
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$output = $key . ' : ' . $val ."\n";
fwrite($myfile, $output);
fclose($myfile);
}
There are two misconceptions in your code:
You are opening a file, write to it and close it for each $key=>$var in $postback_data which is highly ineffective. You should open it once before the loop and close it after completion of the loop.
You are writing to a file instead of appending. Check the modes for fopen().
Here is the code that might do what you desire:
$postback_data = $_REQUEST;
$myfile = fopen("newfile.txt", "a") or die("Unable to open file!");
foreach($postback_data as $key=>$var) {
$output = $key . ' : ' . $val ."\n";
fwrite($myfile, $output);
}
fclose($myfile);
If you wish to create a new file for each request, use the "w" mode on fopen(). Use "a" if you want to append every new request’s POST data to the same file.
Place fopen and fclose outside the loop or use fopen('file.txt', a) instead. fopen('file.txt', w) resets the files and overwrites everything.
If your goal is just saving that information into a file to see it and format is not so important, you can achieve that by using a few built-in functions. You don't need to iterate all over the list using foreach:
$post = var_export($_REQUEST, true);
file_put_contents('newfile.txt', $post);
Beware: $_REQUEST also contains $_COOKIE data besides $_POST and $_GET.
var_export here returns string representation of given variable. If you the omit second argument true, it directly prints it.
If your goal is improving your skills, here is the correct version of your code with some notes:
// prefer camelCase for variable names rather than under_scores
$postbackData = $_REQUEST;
// Open the resource before (outside) the loop
$handle = fopen('newfile.txt', 'w');
if($handle === false) {
// Avoid inline die/exit usage, prefer exceptions and single quotes
throw new \RuntimeException('File could not open for writing!');
}
// Stick with PSR-2 or other well-known standard when writing code
foreach($postbackData as $key => $value) {
// The PHP_EOL constant is always better than escaped new line characters
$output = $key . ' : ' . $value . PHP_EOL;
fwrite($handle, $output);
}
// Close the resource after the loop
fclose($handle);
And don't forget to call your file using some test data in your querystring such as: http://localhost/postback.php?bar=baz Otherwise, both $_RQUEST and the contents of the file would be empty since there is nothing to show.
Good luck and welcome to stack overflow!
Two different values are imported by html <input> tags. They should be displayed like this: value1:value2.
But they display like this instead: value1:value2:.
I know what is causing the problem but I don't know how to solve it because I'm just a beginner with PHP.
?php
$handle = fopen("text.txt", "a");
foreach($_POST as $variable => $value) {
fwrite($handle, $value);
fwrite($handle, ":");
}
fclose($handle);
exit;
?
An option would be to store the data in an array, and glue them together with implode.
foreach($_POST as $key => $value){
$tmp[] = htmlentities($value);
}
if($fp = fopen('text.txt', 'a')){
fwrite($fp, implode(':', $tmp));
fclose($fp);
}
Another solution would be to concat all values to a variable, and strip off the unwanted symbol with trim() or substr() and then write the value of the variable to file.
Also, it might be wise to check if the file successfully opened and depending on what you do with the saved data, to avoid an XSS attack use htmlentites() if you ever plan to echo it.
In every cycle inside the foreach you add a value and the colon. One option is to add the colon before the value is added and don't add it on the first run. Like this:
<?php
$first = true;
$handle = fopen("text.txt", "a");
foreach($_POST as $variable => $value) {
if(!$first) {
fwrite($handle, ":");
$first = false;
}
fwrite($handle, $value);
fclose($handle);
?>
The implode solution from #xorifelse is also nice
I have an issue with writing and reading to text file.
I have to first write from a text file to another text file some values which I need to read again. Below are the code snippets:
Write to text file:
$fp = #fopen ("text1.txt", "r");
$fh = #fopen("text2.txt", 'a+');
if ($fp) {
//for each line in file
while(!feof($fp)) {
//push lines into array
$thisline = fgets($fp);
$thisline1 = trim($thisline);
$stringData = $thisline1. "\r\n";
fwrite($fh, $stringData);
fwrite($fh, "test");
}
}
fclose($fp);
fclose($fh);
Read from the written textfile
$page = join("",file("text2.txt"));
$kw = explode("\n", $page);
for($i=0;$i<count($kw);$i++){
echo rtrim($kw[$i]);
}
But, if I am not mistaken due to the "/r/n" I used to insert the newline, when I am reading back, there are issues and I need to pass the read values from only the even lines to a function to perform other operations.
How do I resolve this issue? Basically, I need to write certain values to a textfile and then read only the values from the even lines.
I'm not sure whether you have issues with the even line numbers or with reading the file back in.
Here is the solution for the even line numbers.
$page = join("",file("text2.txt"));
$kw = explode("\n", $page);
for($i=0;$i<count($kw);$i++){
$myValue = rtrim($kw[$i]);
if(i % 2 == 0)
{
echo $myValue;
}
}
Ok I almost have it working but am having trouble escaping the html to preserve the link I'm missing something here .. I'm sure it's simple
if($_POST['formSubmit'] == "Submit")
$varUserName = $_POST['username'];
$varPW = $_POST['PW'];
$varEmail = $_POST['email'];
{
$fs = fopen("testcsv.csv","a");
fputcsv($fs, array($varUserName,$varPW,$varEmail,"admin","title",",category","some text here site.com",));
fclose($fs);
exit;
}
?>
I am not sure what you're having trouble with. Are you familiar with fopen();? Are you familiar with CSV?
You will need to open the file for appending and append to your file using fwrite(). Once done, close the file with fclose().
$fp = fopen("./filename", 'a'); //Open file for append
//fwrite($fp, $row1.",".$row2); //Append row,row to file
fputcsv($fp, array($name,$password,"http://$name.whatever.com")); //#Optimist
fclose($fp); //Close the file to free memory.