Recipe 23.3. Opening a Remote File

23.3.1. Problem

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

23.3.2. Solution

Pass the file's URL to fopen( ), as in Example 23-7.

Opening a remote file

<?php $fh = fopen('','r') or die($php_errormsg); ?>

23.3.3. 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 filehandle, 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 as shown in Example 23-14.

Using a password with FTP or HTTP

<?php $fh = fopen('','r'); $fh = fopen('','r'); ?>

Opening remote files with fopen( ) is implemented via a PHP feature called the stream 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.

23.3.4. See Also

Recipes 13.1 through 13.7, which discuss retrieving URLs; documentation on fopen( ) at and on stream wrappers at and

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: