WordPress – Comments and X_Forwarded_FOR

This is a patch to comment.php for a wordpress installation.  Basically if the X_FORWARDED_FOR header is set then the comment is attributed to that IP instead of the IP address of the remote connection.  For those that run WordPress behind a reverse proxy, like Squid, Apache, etc. this is helpful.  Of course this header can be spoofed and thus the only way to really know from which IP the connection came is to check the logs on the proxy server.
Now I guess I could get a little more accurate by having the proxy server insert a custom header and then using the value of that header.  Of course that too could be spoofed, etc..  At the end of the day, having the real IP of the device submitting the comment is not all that important anyway.  Though I like having the value of this header more than I like always having the IP of my proxy server.

+++ comment.php Wed Nov 19 01:13:46 2008
@@ -715,7 +715,22 @@
        $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
        $commentdata['user_ID']         = (int) $commentdata['user_ID'];

+/* Original line to get comment users IP
        $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '',$_SERVER['REMOTE_ADDR'] );
+*/
+
+       if ($_SERVER['HTTP_X_FORWARDED_FOR'] != "" ) {
+            $ipAddress = $_SERVER["HTTP_X_FORWARDED_FOR"];
+                if (strpos($ipAddress, ',') !== false) {
+                    $ipAddress = explode(',', $ipAddress);
+                    $ipAddress = $ipAddress[0];
+                }
+
+        } else {
+            $ipAddress = $_SERVER['REMOTE_ADDR'];
+        }
+       $commentdata['comment_author_IP'] = $ipAddress;
+
        $commentdata['comment_agent']     = $_SERVER['HTTP_USER_AGENT'];

        $commentdata['comment_date']     = current_time('mysql');

Speak Your Mind

*


*