How to successfully write a foreach $key=>$var to a textfile - php

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!

Related

PHP. How to read a file, if it is writing without a problem with "a+", but is not readable with "r"?

I have two scripts: one of them writes the value of a variable to a file. In another script, I try to read it. It is written without problems, but it is not readable.
Here I write to a file:
$peer_id=2000000001;
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
$file = fopen($fileLocation,"a+");
fwrite($file, $peer_id);
fclose($file);
Here I read the file:
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
$file = fopen($fileLocation,"r");
if(file_exists($fileLocation)){
// Result is TRUE
}
if(is_readable ($file)){
// Result is FALSE
}
// an empty variables, because the file is not readable
$peer_id = fread($file);
$peer_id = fileread($file);
$peer_id = file_get_contents($file);
fclose($file);
The code runs on "sprinthost" hosting, if that makes a difference. There are suspicions that this is because of that hosting.
file_get_contents in short runs the fopen, fread, and fclose. You don't use a pointer with it. You should just use:
$peer_id = file_get_contents($fileLocation);
That is the same for is_readable:
if(is_readable($fileLocation)){
// Result is FALSE
}
So full code should be something like:
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
if(file_exists($fileLocation) && is_readable($fileLocation)) {
$peer_id = file_get_contents($fileLocation);
} else {
echo 'Error message about file being inaccessible here';
}
The file_get_contents has an inverse function for writing; https://www.php.net/manual/en/function.file-put-contents.php. Use that with the append constant and you should have the same functionality your first code block had:
file_put_contents($fileLocation, $peer_id, FILE_APPEND | LOCK_EX);

create txt file list from php

I have bunch of images file (.jpg) in a folder, then I want to list them to a single file text, I using php (xampp in windows).
This for list images name in my browser (it's working):
<?php
ob_start();
$file='F:\images\upload\google\ready_45';
foreach (glob($file."\*.jpg") as $filenames) {
echo $filenames."<br />";
}
?>
This for create text file called 'images_list.txt' (not working):
<?php
ob_start();
$file='F:\images\upload\google\ready_45';
foreach (glob($file."\*.jpg") as $filenames) {
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
$data = echo $filenames."<br />";
fwrite($handle, $data);
}
?>
When I execute that script, appear warning message
"
Parse error: syntax error, unexpected 'echo' (T_ECHO) in D:\xampp\htdocs\rename_file_php\try_list_img.php on line 7"
If line 7, I change
$data = $filenames;
The file 'images_list.txt' will created, but only fill one image name listing in the file. Can anyone help me?
Sorry for my bad english.
Open file once and try to write data once:-
<?php
ob_start();
$file='F:\images\upload\google\ready_45';
$data = '';
foreach (glob($file."\*.jpg") as $filenames) {
$data .= $filenames."\n";
}
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
fwrite($handle, $data);
fclose($handle);
?>
You want to fopen() the file only once, so outside the loop. Otherwise you overwrite the content again and again. Take a look at this modified version:
<?php
$folder = 'F://images/upload/google/ready_45';
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'w') or die("Cannot open file: ". $my_file);
foreach (glob($folder . "/*.jpg") as $filename) {
$data = $filename . PHP_EOL;
fwrite($handle, $data);
}
fclose($handle);
One certainly could simplify that. For example by simply imploding the list of matched file names with a linebreak and then writing the result in one go:
<?php
$folder = 'F://images/upload/google/ready_45';
$data = implode(PHP_EOL, glob($folder . "/*.jpg"));
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'w') or die("Cannot open file: ". $my_file);
fwrite($handle, $data);
fclose($handle);
However the first (loop based) approach allows more flexibility, for example filtering or escaping.
Side notes:
using a normal slash as folder delimiter (/) instead of the insane backslash (\\) natively used in MS-Windows will save you a lot of hassle. PHP can work with both on a MS-Windows platform.
using a line break instead of the html linewrap makes more sense when writing into a file in most cases. Using PHP_EOL instead of a hard coded line break (\r\n) will make your code portable for systems using different types of line breaks (only MS-Windows uses \r\n for that).
I took the liberty to also fix some indentation and code styling issues. It definitely makes sense if programmers loosely agree on some standard to enhance readability of code.
This is all you need:
// Creates a newline separated list from the array returned by glob()
$files = glob ($folder.'/*.jpg');
$files = implode (PHP_EOL, $files);
∕∕ This is all that is needed to write something to a file.
file_put_contents ($my_file, $files);
The fopen() and all that is old, old code, which should be avoided whenever possible. Not only is this method simpler and easier to read, but it's also generally faster.
Note that you might want to wrap an IF statement around the last line, in order to handle any errors with writing that might crop up.
Following code is working fine, I have a images folder which is having some image files, please change the folder path and try the below code
<?php
ob_start();
$file='images';
foreach (glob($file."\*.jpg") as $filenames) {
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'a') or die('Cannot open file: '.$my_file);
$data = $filenames."\r\n";
fwrite($handle, $data);
}
?>

php save to csv file

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;

Using fwrite() to set a variable in a file

I have two php files: one is called key.php and the other is the function that validates the key. I want to regularly write to the key.php file and update the key from the validator.php file.
I have this code:
$fp = fopen('key.php', 'w');
$fwrite = fwrite($fp, '$key = "$newkey"');
What I'm trying to do is set the $key variable in the file key.php to the value of $new key which is something like $newkey = 'agfdnafjafl4'; in validator.php.
How can I get this to work (use fwrite to set a pre-existing variable in another file aka overwrite it)?
Try this:
$fp = fopen('key.php', 'w');
fwrite($fp, '$key = "' . $newkey . '"');
fclose($fp);
This will "overwrite" the variable in a literal sense. However, it won't modify the one you're using in your script as it runs, you'll need to set it ($key = somevalue).
More to the point, you really should be using a database or a seperate flat text file for this. Modifying php code like this is just plain ugly.
for_example, you have YOUR_File.php, and there is written $any_varriable='hi Mikl';
to change that variable to "hi Nicolas", use like the following code:
<?php
$filee='YOUR_File.php';
/*read ->*/ $temmp = fopen($filee, "r"); $contennts=fread($temp,filesize($filee)); fclose($temmp);
// here goes your update
$contennts = preg_replace('/\$any_varriable=\"(.*?)\";/', '$any_varriable="hi Jack";', $contennts);
/*write->*/ $temp =fopen($filee, "w"); fwrite($temp, $contennts); fclose($temp);
?>

Using php, how to insert text without overwriting to the beginning of a text file

I have:
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
but it overwrites the beginning of the file. How do I make it insert?
I'm not entirely sure of your question - do you want to write data and not have it over-write the beginning of an existing file, or write new data to the start of an existing file, keeping the existing content after it?
To insert text without over-writing the beginning of the file, you'll have to open it for appending (a+ rather than r+)
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
If you're trying to write to the start of the file, you'll have to read in the file contents (see file_get_contents) first, then write your new string followed by file contents to the output file.
$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
The above approach will work with small files, but you may run into memory limits trying to read a large file in using file_get_conents. In this case, consider using rewind($file), which sets the file position indicator for handle to the beginning of the file stream.
Note when using rewind(), not to open the file with the a (or a+) options, as:
If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.
A working example for inserting in the middle of a file stream without overwriting, and without having to load the whole thing into a variable/memory:
function finsert($handle, $string, $bufferSize = 16384) {
$insertionPoint = ftell($handle);
// Create a temp file to stream into
$tempPath = tempnam(sys_get_temp_dir(), "file-chainer");
$lastPartHandle = fopen($tempPath, "w+");
// Read in everything from the insertion point and forward
while (!feof($handle)) {
fwrite($lastPartHandle, fread($handle, $bufferSize), $bufferSize);
}
// Rewind to the insertion point
fseek($handle, $insertionPoint);
// Rewind the temporary stream
rewind($lastPartHandle);
// Write back everything starting with the string to insert
fwrite($handle, $string);
while (!feof($lastPartHandle)) {
fwrite($handle, fread($lastPartHandle, $bufferSize), $bufferSize);
}
// Close the last part handle and delete it
fclose($lastPartHandle);
unlink($tempPath);
// Re-set pointer
fseek($handle, $insertionPoint + strlen($string));
}
$handle = fopen("file.txt", "w+");
fwrite($handle, "foobar");
rewind($handle);
finsert($handle, "baz");
// File stream is now: bazfoobar
Composer lib for it can be found here
You get the same opening the file for appending
<?php
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
If you want to put your text at the beginning of the file, you'd have to read the file contents first like:
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
$existingText = file_get_contents($file);
fwrite($file, $existingText . $_POST["lastname"]."\n");
}
fclose($file);
?>

Categories