Приглашаем посетить
Спорт (www.sport-data.ru)

Connecting with HTTP Servers

Previous
Table of Contents
Next

Connecting with HTTP Servers

<xmp>
<?php
  echo file_get_contents('http://www.php.net/');
?>
</xmp>


Hypertext Transfer Protocol (HTTP) is probably the protocol most often used from PHP to connect with others (apart from various database protocols). Starting with PHP 4.3, it is really easy to connect to such data sources because PHP's stream support was vastly improved in that version (of course, using HTTP in the way this code shows was already possible in earlier PHP releases). The idea is that when you use a file operation, you access a stream of data. In practice, it doesn't really matter whether it's a file on the local system, on a network share, or on a remote server connected via either HTTP, File Transfer Protocol (FTP), or any other supported protocol. Just provide the appropriate filename, and PHP takes care of the rest. The preceding code shows this: It opens the PHP home page and prints its Hypertext Markup Language (HTML) code in the browser. With just one line of code, it cannot get much more simple. Figure 9.1 contains the output.

Figure 9.1. A one-liner prints the HTML markup of the PHP home page.

Connecting with HTTP Servers


WARNING

For security reasons, this behavior can be turned off in php.ini by setting allow_url_fopen to Off, so you cannot rely on it on web servers you cannot controlfor instance, shared hosting at large Internet service providers (ISPs).


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 (http-socket.php)
<?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.

NOTE

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.



Previous
Table of Contents
Next