Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring errors in file_get_contents HTTP wrapper?

The following code is to query an online thesaurus for a search engine I'm building as a college project, but I'm having problems with file_get_contents "failed to open stream" errors. When I send a word the thesaurus doesn't recognize, it throws up an error. I'm trying to write a piece of code that will ignore the error and just proceed without the information.

$thesaurus_search="http://words.bighugelabs.com/api/2/0089388bb57f/".$this->formatted_query."/php";
$result_thesaurus=file_get_contents($thesaurus_search);

I tried:

if (file_get_contents($thesaurus_search) != NULL)
{ // do stuff }

...but its not working because it still returns some sort of string.

What can I do to handle such cases?

like image 239
shanahobo86 Avatar asked Jul 13 '12 17:07

shanahobo86


People also ask

How to fix error of file_get_contents(): http:// wrapper is disabled in the configuration?

How to fix this error? You have to show us the code and tell us what you are trying to do so that someone can help you. Replace file_get_contents with CURL method to resolve Error of file_get_contents (): http:// wrapper is disabled in the server configuration by allow_url_fopen=0

Why can't I open a file with HTTPS in PHP?

file_get_contents () is not allowed to open files with a scheme of https://. The reason for this is your PHP runtime config of allow_url_fopen set to 0. From the Runtime configuration manual: " This option enables the URL-aware fopen wrappers that enable accessing URL object like files.

How to use curl instead of file_get_contents?

@primehalo go to WHM > MultiPHP INI Editor > select PHP version and set allow_url_fopen to Enabled. In my cPanel there is a checkbox to enable allow_url_fopen in (Software)Select PHP Version > Options (tab at the top), although if this doesn't solve it for you see my answer below. Use cUrl instead of file_get_contents.

How to get the contents of a URL using file_get_contents()?

If you are are trying to use file_get_contents () function to fetch the contents of a URL and you receive Error something like Enable the allow_url_fopen parameter in your php.ini configuration. Although this is an easy approach this is not recommended because of the security holes it opens.


1 Answers

If you don't want file_get_contents to report HTTP errors as PHP Warnings, then this is the clean way to do it, using a stream context (there is something specifically for that):

$context = stream_context_create(array(
    'http' => array('ignore_errors' => true),
));

$result = file_get_contents('http://your/url', false, $context);
like image 172
netcoder Avatar answered Oct 06 '22 20:10

netcoder