8.14 Remote filesThis is NOT the latest copy of this book; click here for the latest version.
As you have seen, fopen() is a very helpful function - it allows you to manipulate any files for which you have permission. However, its usefulness is only just beginning - fopen() is even more helpful than you have seen so far!
The key lies in the first parameter to fopen() - 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.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|