11.1 Fetching a Web Page


You have the URL of a Web page and you want to manipulate it as you would a file.

Technique

Use fopen() , which supports the capability of opening URLs:

 <?php $fp = @fopen($url, 'r')     or die("Cannot Open $url via Get method"); while ($line = @fgets($fp, 1024)) {     $contents .= $line; } fclose($fp); ?> 

Or, use the readfile() function:

 $contents = readfile($url); 

Or use PHP's Net_Curl module:

 <?php $conn = new Net_Curl($url); $data = $conn->execute(); print $data; ?> 

Comments

PHP's filesystem functions enable you to read via HTTP and FTP, meaning that you can open URLs and read from them. However, please be aware that the file stat functions are executed through system calls. Therefore, functions such as stat() and filesize() will not work on URLs.

You must also be aware that PHP does not support HTTP redirects. Therefore, if you give PHP a URL such as http://www.designmultimedia.com/programming, it will not work. However, if you give PHP a URL such as http://www.designmultimedia.com/programming/, it will work. Put simply, you must put trailing slashes on directories for PHP to be able to fetch a Web page.

If you want to access a page that requires password authentication, you must use the following form of the URL:

 http://  user:password  @www.designmultimedia.com/protected_dir/ 

where user is the username for the protected directory and password is the corresponding password.

The readfile() function shown in the solution implements the same function as fopen() as far as opening a URL is concerned . However, note that if you use readfile() on a large URL, there is a larger chance that a URL will hang than if you read the file into memory one line at time.

The Net_Curl module from PEAR interfaces with the curl module. To use the Net_Curl module, you need to compile PHP --with-curl support. The Net_Curl extension provides a more powerful interface for accessing the content of Web pages than do the other methods . For example, with Net_Curl , you can connect with SSL servers and connect through proxies.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net