| PHP & Web Development :: PHP Performance + Benchmarking :: Remote File Access | ||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PHP remote file access: fopen() and file_get_contents()
Test Environment: Linux, Apache, PHP 4.3.11 with PHP loaded using FastCGI. Zend Optimizer 2.5.7 installed. What's Zend Optimizer? Test Setup: Code constructs listed below. Refresh the page to execute a new trial!
Discussion: Surprisingly, there is not much difference! I am writing this at 125 trials of the above test, and it looks like fopen() is actually a little faster than file_get_contents(). I checked this again by reversing which test was performed first, and still received the same results. Even testing this script on another URL, the results were the same. So why use file_get_contents()? Well, it is certainly clearer in code structure and because it combines the file open and file read into the same function, you only need to do error handling once. Some situations require the use of fopen(), especially if any writing to the file is required. The sister function to file_get_contents(), file_put_contents(), was not available until PHP 5.0, which is not used yet by many hosting companies. Another set of PHP functionality, the CURL functions, are also very useful and have proven to be much faster than either of the above functions. The problem is that CURL is not compiled with PHP by default, so many users cannot use CURL in a pre-compiled, hosted environment. I have written an object oriented remote file access script using both file_get_contents() and fopen(), depending on which version of PHP is installed on the server. See this script for more information on the usage of fopen() and file_get_contents(). |
||||||||||||||||||