Search code examples
phpfwrite

Store variables in a certain format PHP


I'm trying to store data in a text file in a certain format.

Here is the code:

<?php
header ('Location: http://myshoppingsite.com/ ');
$handle = fopen("userswhobought.txt", "a");
foreach($_POST as $variable => $value) {
    fwrite($handle, $variable);
    fwrite($handle, "=");
    fwrite($handle, $value);
    fwrite($handle, "\r\n");
}
fwrite($handle, "===============\r\n");
fclose($handle);
exit;
?>

So on the previous HTML page they put in 2 value, their name and location, then the php code above would get me their info what they inputted and will store it in the userswhobought.txt

This is how it stores at the moment:

Username=John
Location=UK
commit=
===============

But I simply want it to store like this

John:UK
===============
Nextuser:USA
==============
Lee:Ukraine

So it's easier for me to extract.

Thanks


Solution

  • take your original code

    <?php
    header ('Location: http://myshoppingsite.com/ ');
    $handle = fopen("userswhobought.txt", "a");
    foreach($_POST as $variable => $value) {
        fwrite($handle, $variable);
        fwrite($handle, "=");
        fwrite($handle, $value);
        fwrite($handle, "\r\n");
    }
    fwrite($handle, "===============\r\n");
    fclose($handle);
    exit;
    ?>
    

    and change to

    <?php
    $datastring = $_POST['Username'].":".$_POST['Location']."
    ===============\r\n";
    file_put_contents("userswhobought.txt",$datastring,FILE_APPEND);
    header ('Location: http://myshoppingsite.com/ ');
    exit;
    ?>
    

    Instead of looping through the $_POST data you need to directly manipulate the POST data and then you can use it however you want but I would suggest looking into a database option like mysql, postgres, or sqlite - you can even store data in nosql options like mongodb as well.