PHP

Handling PHP file_get_contents error

Posted on

I have script that request some file to other url. It works great, until it returns error. By default, in their documentation, it has no mention about catching error throwing by this function. Later when i have time to dig further, i found a solution that can catch file_get_contents error message and do what you want.

Reference: https://www.php.net/manual/en/function.file-get-contents.php, https://www.php.net/manual/en/context.http.php

$options  = [
	'http' => [
		'method'     =>"GET",
	],
	'ssl' => [
		"verify_peer"      => FALSE,
		"verify_peer_name" => FALSE,
	],
];

$context  = stream_context_create($options);

$response = file_get_contents($url, FALSE, $context);

echo $response

Now, i have to add some logic to handle the error message.

if (!$response= file_get_contents("http://www.google.com")) {
      $error = error_get_last();
      echo "HTTP request failed. Error was: " . $error['message']."\n";
} else {
      echo "Everything went better than expected";
}

That’s all you can do everything you want.

Leave a Reply

Your email address will not be published. Required fields are marked *