Record IP Address On PHP Form Submit

27 Mar 2013

When receiving questions or feedback from an online survey, sometimes it's nice to use a basic PHP-to-email form instead of a database, as long as you don't plan on getting too many emails to handle.

A possible drawback of this approach is that typically it isn't a smart form, allowing users to resubmit. This could result in a potential issue with unhappy or disruptive users sending multiple forms while you're under the impression that they are coming from multiple sources.

An easy way around this problem is to add a hidden field that records and sends the IP address along with the rest of the survey information.

<form action="" method="post">
    <input type="hidden" name="ip" value="<?php echo $_SERVER['REMOTE_ADDR']; ?>" />

    <!-- the rest of the form //-->


Then simply add it to your PHP code.

$ip = $_POST['ip'];

And include it in the email body.

$email_body .= "IP Address: \r\n$ip\r\n\r\n";

Now when you receive an email from the survey page, it will include the sender's IP address before any of the answers.