I admit, the title of this article is somewhat misleading. The PHP function file_get_contents(), which can be used to read files from the internet into a string, just does not work with allow_url_fopen disabled. On that not even this article will change anything.
However, if you want to develop an application or a script, that should work on as many server environments as possible, such as a wordpress plugin, so there is a good workaround for all the environments where allow_url_fopen is disabled. And just this little snippet/workaround is what I want to show and explain to you today.
$file = "http://www.example.com/my_page.php"; if (function_exists('curl_version')) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $file); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $content = curl_exec($curl); curl_close($curl); } else if (file_get_contents(__FILE__) && ini_get('allow_url_fopen')) { $content = file_get_contents($file); } else { echo 'You have neither cUrl installed nor allow_url_fopen activated. Please setup one of those!'; }
First, it is checked whether the cURL extension is available on the server. If this is the case, the file is loaded via cURL. If cURL is not available, it is checked if allow_url_fopen is enabled. If this is the case, the file is loaded via file_get_contents().
If both options are not available, an error message is displayed, what should protect the enduser from seeing, for him maybe “cryptic”, error messages.
If you wonder why I give cURL preference over file_get_contents(), the reason is that I’ve made the experience that cURL has somewhat better performance.
In conclusion it can be said, that using the workaround outlined here, the chance that your script is running at as many environments as possible, can be doubled. (Doubled due to the fact you’ll provide two methods for downloading files to the server.) That’s quite something, isn’t it?
What do you think about my snippet? Would you implement it in the same way? How do you deal with the “problem” of deactivated allow_url_fopen?
Where do you place this script?
thank you!