php_network_getaddresses: getaddrinfo failed: Name or service not known

Here is a snippet of my code

$fp = fsockopen($s['url'], 80, $errno, $errstr, 5);
if($fp){
        fwrite($fp, $out);
        fclose($fp);

When I run it, it outputs:

unable to connect to www.mydomain.net/1/file.php:80 (php_network_getaddresses: getaddrinfo failed: Name or service not known

I'm using this to submit GET data to the $s['url']

I can't figure out why. Any help would be greatly appreciated.


Solution 1:

You cannot open a connection directly to a path on a remote host using fsockopen. The url www.mydomain.net/1/file.php contains a path, when the only valid value for that first parameter is the host, www.mydomain.net.

If you are trying to access a remote URL, then file_get_contents() is your best bet. You can provide a full URL to that function, and it will fetch the content at that location using a normal HTTP request.

If you only want to send an HTTP request and ignore the response, you could use fsockopen() and manually send the HTTP request headers, ignoring any response. It might be easier with cURL though, or just plain old fopen(), which will open the connection but not necessarily read any response. If you wanted to do it with fsockopen(), it might look something like this:

$fp = fsockopen("www.mydomain.net", 80, $errno, $errstr, 30);
fputs($fp, "GET /1/file.php HTTP/1.1\n");
fputs($fp, "Host: www.mydomain.net\n");
fputs($fp, "Connection: close\n\n"); 

That leaves any error handling up to you of course, but it would mean that you wouldn't waste time reading the response.

Solution 2:

I had a similar problem on my local testserver and local testdomains e.g.: www.testdomain.loc with the function GetImageSize();

Solved it by adding the hostname in the hosts file on the local server:

In the file /etc/hosts I added:

192.168.1.1 www.testdomain.loc

Hope this helps anyone