Neon Flash
Neon Flash

Reputation: 3233

PHP Socket GET Request

I am using the following script to send a GET request to a site however, I keep getting the error, No response from the Server.

  1. I have run wireshark to see any traffic being generated as a result of running this script, but there is no traffic.
  2. I can connect to the site from the Browser and I can also retrieve the contents by using the file_get_contents function, however using sockets, I am unable to do it.

Here is the code which makes use of sockets to send the request to the site and it returns the error: "No response from the Server" if the connection was not successful.

<?php

error_reporting(0);
set_time_limit(0);
ini_set("default_socket_timeout", 5);

function http_send($host, $packet)
{
    if (!($sock = fsockopen($host, 80)))
        die( "\n[-] No response from {$host}:80\n");

    fwrite($sock, $packet);
    return stream_get_contents($sock);
}

$host="http://example.com";
$path="/";
$packet  = "GET {$path} HTTP/1.0\r\n";
$packet .= "Host: {$host}\r\n";
$packet .= "Connection: close\r\n\r\n";

http_send($host, $packet);

?>

So, what is wrong in the code above that it is unable to send the GET request?

It appears ok to me, it will form the HTTP Request Headers for the GET request and store in the $packet variable.

$host is the destination site name.

Then it calls the function, http_send which will send the request.

Error Output: [-] No response from http://example.com:80

Upvotes: 2

Views: 12113

Answers (2)

Arun Killu
Arun Killu

Reputation: 14233

$fp = fsockopen("127.0.0.1", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET /out.php HTTP/1.1\r\n";
    $out .= "Host: 127.0.0.1\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}

out.php contains

 <?php
 echo 'got in';

output obtained

 HTTP/1.1 200 OK Date: Mon, 05 Nov 2012 08:23:11 GMT Server: Apache/2.2.21 (Win32)
     mod_ssl/2.2.21 OpenSSL/1.0.0e PHP/5.3.8 mod_perl/2.0.4 Perl/v5.10.1 X-Powered-By: 
    PHP/5.3.8 Content-Length: 6 Connection: close Content-Type: text/html got in

Upvotes: 4

Mitch Satchwell
Mitch Satchwell

Reputation: 4830

Look at the error being returned by fsockopen by passing in parameters for errno and errstr:

if (!($sock = fsockopen($host,80,$err_no,$err_str)))
    die($err_no.': '.$err_str);

Upvotes: 1

Related Questions