1

Hello I have created an email form but am very unfamiliar with how to code in a section that displays a users IP address in the email that is sent. Here is my code.

Endô Fujimoto
  • 313
  • 1
  • 5
  • 15

1 Answers1

1

You can't be sure of the real IP of the person using your email form because they could be behind a proxy or VPN, but this is a way to get the best candidate IP address at the time of the visit (ref):

function getUserIP() {
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    if(filter_var($client, FILTER_VALIDATE_IP)) {
        $ip = $client;
    } else if(filter_var($forward, FILTER_VALIDATE_IP)) {
        $ip = $forward;
    } else {
        $ip = $remote;
    }
    return $ip;
}

Then you can add the IP information to your email body with

$myMessage .= "Sent from IP: " . getUserIP() . ".";

Further reading: What is the difference between HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR?

Community
  • 1
  • 1
Drakes
  • 23,254
  • 3
  • 51
  • 94