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.
Asked
Active
Viewed 164 times
1
-
There is no code related to IP addresses in your question. What have you tried? – Drakes Jun 14 '15 at 23:09
-
Not sure where to start. I've never worked with IP addresses in code before. I tried to google it but had no luck. – Endô Fujimoto Jun 14 '15 at 23:09
-
You want to include your IP address from the email server, or you want to put the recipient's IP address in the email body? – Drakes Jun 14 '15 at 23:11
-
I would like to put the recipients ip address in the email body – Endô Fujimoto Jun 14 '15 at 23:12
-
IP does not uniquely identify a user, so its kind of useless – Jun 14 '15 at 23:15
-
I want it in there though because I have always wanted to try it out. Any help would be much appreciated – Endô Fujimoto Jun 14 '15 at 23:15
1 Answers
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?
-
-
$myMessage = $myNameLabel .' '. $_POST["m_name".$unique_id].', '. $myEmailLabel .' '. $_POST["m_email".$unique_id].', '. date("r"); – Endô Fujimoto Jun 14 '15 at 23:24
-
`$myMessage .=` (notice the dot) appends more text to `$myMessage`, so you can use the line supplied in my answer to add the IP info to end of your message. – Drakes Jun 14 '15 at 23:26
-
Alternatively, `$myMessage = $myNameLabel .' '. $_POST["m_name".$unique_id].', '. $myEmailLabel .' '. $_POST["m_email".$unique_id].', '. date("r") . ', ' . getUserIP();` – Drakes Jun 14 '15 at 23:27
-
-
Worked fantastic. Sorry mate for not replying. Really appreciate the help – Endô Fujimoto Jun 15 '15 at 23:07