posted by kevin on April 14, 2009

Why would you need a replacement?

I used to love using file_get_contents on remote files because it was a simple, single function call to get remote data that I needed. However for security issues I decided that we should probably disable the PHP INI setting 'allow_url_fopen'. When you disable allow_url_fopen, it pretty much cuts the balls off of file_get_contents for remote files.

So naturally I wanted to build a function that would emulate file_get_contents for remote files.

See how easy it was to use this...

<?php
$xml_string = file_get_contents("http://www.medicalnewstoday.com/rss/abortion.xml");
?>

Since cURL is pretty much the de facto standard for making HTTP requests in PHP I decided to use that as my base.

A few years ago i also started building a 'toolkit' of classes and methods that I use from time to time so I figured this would make a nice addition. Being that It deals with HTTP requests I thought I'd name it CA_HTTP. The CA really stands for the company I work for, Creative Anvil. Every class in the toolkit is prefaced with CA_ so I can actually just put my 'toolkit' on the server in one place and then access it from all the sites.

This is a simplified version of the class with only the file_get_contents replacement.

<?php
class CA_HTTP {
 
    public static function get_contents($url) {
        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_HEADER, 0);
        ob_start();
        curl_exec ($ch);
        curl_close ($ch);
        return ob_get_clean();  
    }
 
}
?>

So then calling this in my code is almost the same as the file_get_contents..

<?php
$url = "http://www.yahoo.com";
//old, unavailable but great function.
$content1 = file_get_contents($url);
 
//new, based on curl
$content2 = CA_HTTP::get_contents($url);
?>
 

One comment to "Replacement For file_get_contents (using cURL)"

#93
AntonioCS says:
December 7, 2009 at 04:04 am
There is no need for ob_start. If you use the CURLOPT_RETURNTRANSFER option in curl_setopt the data will be returned instead being output out directly.
Bookmark and Share

Leave a Comment

Your email address will not be published.

(You can enclose code in <php></php> blocks.)

You may use Markdown syntax.

Please enter the letters as they are shown in the image above.
Letters are not case-sensitive.