PHP workaround – how to use file_get_contents() without allow_url_fopen
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 […]