Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP How To Send Raw HTTP Packet

I want to send a raw http packet to a webserver and recieve its response but i cant find out a way to do it. im inexperianced with sockets and every link i find uses sockets to send udp packets. any help would be great.

like image 813
Ozzy Avatar asked Sep 22 '09 23:09

Ozzy


2 Answers

Take a look at this simple example from the fsockopen manual page:

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

The connection to the server is established with fsockpen. $out holds the HTTP request that’s then send with frwite. The HTTP response is then read with fgets.

like image 143
Gumbo Avatar answered Sep 30 '22 13:09

Gumbo


If all you want to do is perform a GET request and receive the body of the response, most of the file functions support using urls:

<?php

$html = file_get_contents('http://google.com');

?>

<?php

$fh = fopen('http://google.com', 'r');
while (!feof($fh)) {
    $html .= fread($fh);
}
fclose($fh);

?>

For more than simple GETs, use curl (you have to compile it into php). With curl you can do POST and HEAD requests, as well as set various headers.

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://google.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$html = curl_exec($ch);

?>
like image 42
Dana Avatar answered Sep 30 '22 13:09

Dana