Like many others I’ve used the native PHP function file_get_contents() to receive the content from a remote file because the functions is very easy to use. But is it the best way to do that? I see many scripts using that function and even WordPress plugins are using this function while WordPress has a native function to receive remote content.
While debugging some website, I’ve noticed that I get trouble using file_get_contents() if I use the 5G firewall rules for the remote site I tried to access. This native PHP function doesn’t send any USER AGENT information and that’s why a 5G rules has blocked the access. There are also other reasons to use other functions: Missing response codes, no option to add additional headers and limitations from your hosting provider are just a view of them.
The file_get_contents() CURL alternative
I like CURL a lot, because there are so many options you can use. Do you ever tried to access password protected directory or FTP transport?
The simple function below is a good replacement for the PHP function file_get_contents() and accepts exact the same URL parameter.
function file_get_contents_curl($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36'); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); $data = curl_exec($ch); $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($retcode == 200) { return $data; } else { return null; } }
Maybe your like to change check for the $retcode to accept other HTTP response codes as valid values:
if (in_array($retcode, array('200', '304'))) {
The WordPress variant for file_get_contents()
I mentioned before there is a native WordPress function that is able to do the same as file_get_contents(). The function wp_remote_get() is works almost the same and accepts some additional arguments.
<?php $args = array( 'timeout' => 5, 'redirection' => 5, 'httpversion' => '1.0', 'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ), 'blocking' => true, 'headers' => array(), 'cookies' => array(), 'body' => null, 'compress' => false, 'decompress' => true, 'sslverify' => true, 'stream' => false, 'filename' => null ); ?>
The response is not a string but some array. This example shows how to get the returned headers and body (content).
$response = wp_remote_get( 'http://www.example.com/index.php?action=foo', array( 'timeout' => 120, 'httpversion' => '1.1' ) ); if( is_array($response) ) { $header = $response['headers']; // array of http header lines $body = $response['body']; // use the content }
For myself there is no reason to use file_get_contents() in any future project. How about you, do you go for “quick and dirty” or do you prefer the secure and comfortable way?