Nov 22, 2008
Having PHP Problems With JSON and file_get_contents()?
Chances are your webhost doesn’t allow this type of access for security reasons.
If you are even remotely handy with PHP, there is a very simple fix: Using CURL.
First, open the PHP file that is giving you the problem (make a backup of the original, just in case!).
Second, add this function to the file (make sure you do it outside of any other function definitions, and preferebly before you use it in the rest of the file…):
// function to replace file_get_contents()
function new_get_file_contents($url) {
$ch = curl_init();
$timeout = 10; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_ e x e c($ch); // take out the spaces of curl statement!!
curl_close($ch);
return $file_contents;
}
Then, search through your file for “file_get_contents” and then replace those words with “new_get_file_contents”. In a nutshell, you are replacing the original function that doesn’t work on your webhost (file_get_contents() ) with one that WILL work on your host (new_get_file_contents() ).
I usually leave a commented out copy the original line in the source, so that I can easily go back to the original if necessary.
So, for example:
$myVar = file_get_contents($url);
becomes:
// $myVar = file_get_contents($url);
$myVar = new_file_get_contents($url);
Pretty easy! I’m not sure that this will work in all situations, but I have yet to find a place where it doesn’t work. I was easily able to replace file_get_contents() with CURL in about 5 minutes in altPWA, an excellent Wordpress Plugin for adding Picasa photos and albums to your blog.
Nice and easy!
Wordpress, web development, PHP, CURL, file_get_contents, JSON 





0 comments
Got something important to say? Fill out the form below...
Leave a Comment