phpcurlpage-curlphp-curl

How to use a user IP with PHP/cURL?


I have a server, but cURL is using server's IP address. I want cURL to use the IP address of the person entering the server.

How can I do this?


Solution

  • You want to make an HTTP request that fools the remote server into thinking that is comes from the IP address of your user. This is not possible. The IP address of the user is not included in the HTTP request; the value you get in $_SERVER['REMOTE_ADDR]` comes from the IP protocol.

    However, you can act as a proxy for your user. It seems you already know that but you could not figure out the correct way to do it.

    Indeed, you have to add a header to your request to the remote server. However, the argument you pass to CURLOPT_HTTPHEADER is a list of HTTP requests that are written verbatim into the request cUrl sends.

    This means your code should read:

    curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Forwarded-For: $ip"));
    

    Be warned that the remote server can ignore the header, either because the programmer overseen the possibility of the clients to use an HTTP proxy or because the header can be easily forged. If it ignores it then it uses the IP address of your server as client IP address (which is what you want to avoid in the first place).

    Read more about the X-Forwarded-For HTTP header.