PHP

Connecting HTTP Servers using fsockopen

If you want to control the HTTP request by yourself, you can do so by using sockets. First, open a socket with fsockopen() to the web server, and if that works, then send a well-formed HTTP request. The following code implements this again for querying the PHP home page.

Reading in an HTTP resource using sockets

<?php
  $fp = @fsockopen('www.php.net', 80, $errno,
    $errstr, 30);
  if ($fp) {
    echo '<xmp>';
    $request = "GET / HTTP/1.0\r\n";
    $request .= "Host: www.php.net\r\n";
    $request .= "Connection: Close\r\n\r\n";
    fwrite($fp, $request);
    while (!feof($fp)) {
      echo fgets($fp, 1024);
    }
    fclose($fp);
    echo '</xmp>';
  } else {
    echo "Error: $errstr (#$errno)";
  }
?>

The output is the same, with one difference: The socket approach also returns all HTTP headers sent by the server, whereas the stream wrappers omit them.

When it is required to work with HTTP Secure (HTTPS) resources (websites secured with SSLSecure Sockets Layer), the two approaches still work, although with slight modification:

  • When using file functions such as file_get_contents(), just provide an https:// uniform resource locator (URL).

  • When using sockets, use an ssl:// URL.

by BrainBellupdated
Advertisement: