Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

18.3. Opening a Remote File

Problem

You want to open a file that’s accessible to you via HTTP or FTP.

Solution

Pass the file’s URL to fopen( ) :

$fh = fopen('http://www.example.com/robots.txt','r') or die($php_errormsg);

Discussion

When fopen( ) is passed a filename that begins with http://, it retrieves the given page with an HTTP/1.0 GET request (although a Host: header is also passed along to deal with virtual hosts). Only the body of the reply can be accessed using the file handle, not the headers. Files can be read, not written, via HTTP.

When fopen( ) is passed a filename that begins with ftp://, it returns a pointer to the specified file, obtained via passive mode FTP. You can open files via FTP for either reading or writing, but not both.

To open URLs that require a username and a password with fopen( ), embed the authentication information in the URL like this:

$fh = fopen('ftp://username:password@ftp.example.com/pub/Index','r');
$fh = fopen('http://username:password@www.example.com/robots.txt','r');

Opening remote files with fopen( ) is implemented via a PHP feature called the URL fopen wrapper . It’s enabled by default but is disabled by setting allow_url_fopen to off in your php.ini or web server configuration file. If you can’t open remote files with fopen( ), check your server configuration.

See Also

Section 11.2 through Section 11.6, which discuss retrieving URLs; documentation on fopen( ) at http://www.php.net/fopen and on the URL fopen wrapper feature at http://www.php.net/features.remote-files ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata