GreyCode Developers
GreyCode Developers

Reputation: 1

How do i set ip address when using file_get_content() in php?

I am using file_get_content() to open a file from external url. But when i do so, the url request ip is being set as the server ip instead of the client ip. is there any way to solve this?

I found this by testing the following code.

<?php
$ip = $_SERVER['REMOTE_ADDR'];
// Create a stream
$opts = array(
        'http'=>array(
            'method'=>"GET",
            'header'=>"HTTP_CLIENT_IP: $ip" .
            "remote_addr: $ip".
            "server_addr: $ip".
            "Cookie: foo=bar\r\n",
            )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('http://ifconfig.me/ip', false, $context);
var_dump($file);

Output : string(10) "153.92.0.6" (It is my domain ip) Output i wanted is client ip instead of domain ip

Upvotes: 0

Views: 1230

Answers (1)

Quentin
Quentin

Reputation: 944256

the url request ip is being set as the server ip instead of the client ip.

Well yes. That is where the request is coming from.

is there any way to solve this?

Make the request from the client instead. e.g. with Ajax. Expect the same origin policy to get in the way.


If your goal is to get the client's IP address, then $_SERVER['REMOTE_ADDR'] already has that and you have no need to go to an external service.

Upvotes: 1

Related Questions