如何成功地将foreach $ key => $ val写入文本文件

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 ."
";
        fwrite($myfile, $output);
        fclose($myfile);
    }

Place fopen and fclose outside the loop or use fopen('file.txt', a) instead. fopen('file.txt', w) resets the files and overwrites everything.

There are two misconceptions in your code:

  1. 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.
  2. 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 ."
";
  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.

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!