Search code examples
phpfsockopen

fsockopen have errors : HTTP/1.1 301 Moved Permanently and 404


I have used this code to open whatismyipaddress.com

$fp = fsockopen("whatismyipaddress.com", 80, $errno, $errstr, 5);

if ($fp) {
    $url = "/";

    fputs($fp, "GET $url HTTP/1.1\r\nHost: {whatismyipaddress.com}\r\nConnection: close\r\n\r\n");
    $resp = '';

    while(!feof($fp)) {
        $resp .= fgets($fp, 1024);
    }

    echo "$resp";
}

and i always can see this error

HTTP/1.1 301 Moved Permanently Date: Tue, 29 Nov 2011 20:19:36 GMT Server: Apache/2.2.17 (Unix) DAV/2 Location: http://whatismyipaddress.com/ MS-Author-Via: DAV Content-Length: 0 Connection: close Content-Type: text/html

Also i have used this code to open whatismyipaddress.com/proxy-check

$fp = fsockopen("whatismyipaddress.com", 80, $errno, $errstr, 5);

if ($fp) {
    $url = "/proxy-check";

    fputs($fp, "GET $url HTTP/1.1\r\nHost: {whatismyipaddress.com}\r\nConnection: close\r\n\r\n");
    $resp = '';

    while(!feof($fp)) {
        $resp .= fgets($fp, 1024);
    }

    echo "$resp";
}

and have this error

HTTP/1.1 404 Not Found Date: Tue, 29 Nov 2011 20:32:07 GMT Server: Apache/2.2.17 (Unix) DAV/2 Content-Length: 421 Connection: close Content-Type: text/html; charset=iso-8859-1 Not Found

The requested URL /proxy-check was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. Apache/2.2.17 (Unix) DAV/2 Server at {whatismyipaddress.com} Port 80

I'm sure, there is no any problem with the codes. i have tested it with many sites and i didn't get any problem

Please can anyone explain this problem ?

Thank you.


Solution

  • Basically your script works fine. There are some errors. One is specific to HTTP, see this line of code:

    fputs($fp, "GET $url HTTP/1.1\r\nHost: {whatismyipaddress.com}\r\nCon ...
                                           ^                     ^
    

    Remove those brackets, the HTTP protocol does not have any of those there, you need to provide a valid hostname. Solution:

    fputs($fp, "GET $url HTTP/1.1\r\nHost: whatismyipaddress.com\r\nCon ...
    

    Then the remote site will tell you need a user agent. Add it as an additional header:

    fputs($fp, "GET $url HTTP/1.1\r
    Host: whatismyipaddress.com\r
    Connection: close\r
    User-Agent: Florian der Fensterputzer\r\n\r\n");
    

    This will do it. Demo.