Communicating with Others

Most of the previous tutorials worked within the ecosystem of the PHP script and the web server in use. However, because some tutorials can also be understood by others, this tutorial covers some examples of this type. You can connect to remote servers in a variety of ways.

Connecting with HTTP Servers

Using file_get_contents

  echo file_get_contents('');

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.

Note: 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).

by BrainBellupdated