As you have seen, file_get_contents() and fopen() are very helpful functions - they allow you to manipulate any files for which you have permission. However, its usefulness is only just beginning...
The key lies in the first parameter to both of these functions: rather than using local file names, you can specify remote files also - even files stored on HTTP and FTP servers. PHP automatically opens a HTTP/FTP connection for you, returning the file handle as usual. For all intents and purposes, a file handle returned from a remote file is good for all the same uses as a local file handle. Let's take a look at an example of reading a remote file through fopen():
<?php $slash = fopen("http://www.slashdot.org", "r"); $site = fread($slash, 200000); fclose($slash); print $site; ?>
Try saving the above code into a file, "openremote.php", and loading it into your web browser - you should see Slashdot displayed. What happens behind the scenes is that when your PHP script executes, it opens a connection the Slashdot server, downloads the default web page, and then transfers it to you as if it were part of your site. Notice how the "r" mode is specified - web servers do not allow writing through HTTP (without WebDAV), and some will even deny access for reading if you are an anonymous visitor, as PHP normally is.
Over FTP, however, you are able to read and write, so you are able to upload and download files freely using fopen() and an FTP connection.
Author's Note: If you are looking to find a quick way to execute an external script, you should try using fopen(). For example, to call foo.php on example.com, use fopen("www.example.com/foo.php", "r"). You need not bother reading in the results - simply opening the connection is enough to make the server on example.com process the contents of foo.php.
Next chapter: File checksums >>
Previous chapter: One last directory function
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.