How to continue PHP loop if you get a Warning? - php

OK so i have a list of urls and one of them is missing which is all good but how do i continue the loop instead of it stopping and giving me a warning error
foreach ($AllVideoThumbnails as $thumbnail) {
try {
GenerateImageCache($thumbnail['youtubethumbnail']);
}
catch (Exception $e) {
// echo 'Message: ' .$e->getMessage();
// continue;
}
}
And one the one with the image missing it gives this error
Warning: exif_imagetype(https://i.ytimg.com/vi/X8AurWRkRpo/hqdefault.jpg): failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found in C:\wamp64\www\ModelHurdV2\ImageCache.php on line 400
And there is no image but I want to the finish the loop and just that error al together
this is the contents of Generate Image Cache
require_once 'ImageCache.php';
$imagecache = new ImageCache\ImageCache();
$imagecache->cached_image_directory = dirname(__FILE__) . '/cached';
$cached_src_one = $imagecache->cache($imageUrl);
And this is the cache I am using
https://github.com/nielse63/php-image-cache

Related

Php-fpm still logging my error even when using catch

Php-fpm error log file is still logging my error even using try-catch
$NUM_OF_ATTEMPTS = 100;
$attempts = 0;
do
{
try
{
$db = new SQLite3('proxies/socks5.db');
$results = $db->query('SELECT proxy FROM socks5proxies WHERE timeout <= ' . $settimeout . $countryq . ';');
while ($row = $results->fetchArray())
{
echo $row['proxy'] . "\r\n";
}
}
catch(Exception $e)
{
$attempts++;
sleep(1);
continue;
}
break;
}
while ($attempts < $NUM_OF_ATTEMPTS);
Expected result:
Retry on error, and don't log the error
Actual results:
Logs the error in the php-fpm error log file:
thrown in /var/www/html/api.php on line 200
[10-Jan-2019 14:00:49 UTC] PHP Warning: SQLite3::query(): Unable to prepare statement: 11, database disk image is malformed in /var/www/html/api.php on line 140
[10-Jan-2019 14:00:49 UTC] PHP Fatal error: Uncaught Error: Call to a member function fetchArray() on boolean in /var/www/html/api.php:141
Stack trace:
#0 {main}
thrown in /var/www/html/api.php on line 141
Call SQLite3::enableExceptions to tell PHP it should throw exceptions instead of standard errors:
try {
$db = new SQLite3('proxies/socks5.db');
$db->enableExceptions(true);
$results = $db->query('...');
} catch (\Exception $e) {
}
In any case, if you need to do 100 attempts to get this to work, then this really isn't the angle you should be taking to fix it.

Unable to catch PHP file_get_contents error using try catch block [duplicate]

This question already has answers here:
HTTP requests with file_get_contents, getting the response code
(6 answers)
Closed 8 months ago.
I am trying to fetch an image using file_get_contents function but it gives an error. To handle the error I am using try catch block but it does not catch the error and fails.
My code:
try {
$url = 'http://wxdex.ocm/pdd.jpg'; //dummy url
$file_content = file_get_contents($url);
}
catch(Exception $e) {
echo 'Error Caught';
}
Error:
Warning: file_get_contents(): php_network_getaddresses: getaddrinfo failed: No such host is known
Warning: file_get_contents(http://wxdex.ocm/pdd.jpg): failed to open stream: php_network_getaddresses: getaddrinfo failed: No such host is known.
NOTE:: I am able to fetch any other valid image url on remote.
try/catch doesn't work because a warning is not an exception.
You can try this code so you can catch warnings as well.
//set your own error handler before the call
set_error_handler(function ($err_severity, $err_msg, $err_file, $err_line, array $err_context)
{
throw new ErrorException( $err_msg, 0, $err_severity, $err_file, $err_line );
}, E_WARNING);
try {
$url = 'http://wxdex.ocm/pdd.jpg';
$file_content = file_get_contents($url);
} catch (Exception $e) {
echo 'Error Caught';
}
//restore the previous error handler
restore_error_handler();
Following is the altenative way , just need to check for the data , if not we can throw the exception to handle it. it will be safer compared with setting the new error handler
try {
$url = 'http://wxdex.ocm/pdd.jpg';
$file_content = file_get_contents($url);
if(empty($file_content)){
throw new Exception("failed to open stream ", 1);
}else{
echo "File is loaded and content is there";
}
} catch (Exception $e) {
echo 'Error Caught';
}
check URL exist before that using get header function
$url = 'http://wxdex.ocm/pdd.jpg';
$file_headers = #get_headers($url);
if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found' ||trim($file_headers[0]) == 'HTTP/1.1 403 Forbidden') {
$exists = false;
}else{
$exists = true;
}
if($exists===true){
$file_content = file_get_contents($url);
}

fgets() halting without error in Swiftmailer

I'm attempting to generate a test email in Laravel 4.2 (Windows 7, IIS 6.1), and I've encountered a silent termination - it just fails, doesn't return my view, and doesn't return an error or Exception. I've managed to brute force my way through the Laravel codebase and located the termination within Swift\Transport\AbstractSmtpTransport::_getFullResponse(), specifically the line $line = $this->_buffer->readLine($seq);:
protected function _getFullResponse($seq)
{
$response = '';
try {
do {
$line = $this->_buffer->readLine($seq);
$response .= $line;
} while (null !== $line && false !== $line && ' ' != $line{3});
} catch (Swift_IoException $e) {
$this->_throwException(
new Swift_TransportException(
$e->getMessage())
);
} catch (Swift_TransportException $e) {
$this->_throwException($e);
}
return $response;
}
That do loop executes twice. The first time $line is assigned the value * OK The Microsoft Exchange IMAP4 service is ready., which is great, as obviously I'm getting to the server. Unfortunately, the second iteration fails in Swift\Transport\StreamBuffer::readLine() at the line $line = fgets($this->_out); :
public function readLine($sequence)
{
if (isset($this->_out) && !feof($this->_out)) {
$line = fgets($this->_out);
if (strlen($line)==0) {
$metas = stream_get_meta_data($this->_out);
if ($metas['timed_out']) {
throw new Swift_IoException(
'Connection to ' .
$this->_getReadConnectionDescription() .
' Timed Out'
);
}
}
return $line;
}
}
I've tried wrapping that line in a try/catch, and nothing happens, the code just halts with no information on the second iteration of the do loop. So, any advice as to a) how to squeeze more information out of the halt or b) what could cause fgets() to halt this way?
Ok, progress: after broadening my search to Swiftmailer in general, I was able to find mention of a timeout occurring at that particular line in Swiftmailer. By extending the max_execution_time in php.ini I was able to get an actual Exception:
Expected response code 220 but got code "", with message "* OK The Microsoft Exchange IMAP4 service is ready. * BYE Connection is closed. 13 "
I think under the circumstances I'll close this question and move onto figuring out why I'm not getting a 220.

PHP file_get_contents by an 404

I'm getting JSON arrays with file_get_contents, but if the page doesn't exist I want to give an message: Player not found. But now I get this error:
Warning: file_get_contents(urlwithan404errorhere)
[function.file-get-contents]: failed to open stream: HTTP request
failed! HTTP/1.1 404 Not Found in -------
I don't get this error when the api gives me an correct JSON array.
This is the code is use:
$gegevens = file_get_contents('');
$array_2 = json_decode($gegevens, TRUE);
$summonerid = $array_2[$naam]["id"];
Your code could become like this:
$gegevens = #file_get_contents('');
if ($gegevens !== FALSE) {
$array_2 = json_decode($gegevens, TRUE);
$summonerid = $array_2[$naam]["id"];
} else {
$summonerid = 0;
}
Explanations:
* the # in front of file_get_contents is to stop showing php error in case the request failed.
* if the $summonerid equals to 0, then you have no player found
Try something like this:
if (($gegevens = #file_get_contents('')) === false) {
printf("<h1>Player not found!</h1>\n");
return;
}
// ... continue here ...
The # will suppress any error message if file_get_contents()fails. It will return falsein this case (use === for comparison to avoid confusion with empty files), which you can use for failure detection.

Ignoring PHP error, while still printing a custom error message

So:
#fopen($file);
Ignores any errors and continues
fopen($file) or die("Unable to retrieve file");
Ignores error, kills program and prints a custom message
Is there an easy way to ignore errors from a function, print a custom error message and not kill the program?
Typically:
if (!($fp = #fopen($file))) echo "Unable to retrieve file";
or using your way (which discards file handle):
#fopen($file) or printf("Unable to retrieve file");
Use Exceptions:
try {
fopen($file);
} catch(Exception $e) {
/* whatever you want to do in case of an error */
}
More information at http://php.net/manual/language.exceptions.php
slosd's way won't work. fopen doesn't throw an exception. You should thow it manually
I will modify your second exaple and combine it with slosd's:
try
{
if (!$f = fopen(...)) throw new Exception('Error opening file!');
}
catch (Exception $e)
{
echo $e->getMessage() . ' ' . $e->getFile() . ' at line ' . $e->getLine;
}
echo ' ... and the code continues ...';
Here's my own solution. Note that it needs either a script-level global or a static variable of a class for easy reference. I wrote it class-style for reference, but so long as it can find the array it's fine.
class Controller {
static $errors = array();
}
$handle = fopen($file) or array_push(Controller::errors,
"File \"{$file}\" could not be opened.");
// ...print the errors in your view
Instead of dying you could throw an exception and do the error handling centrally in whichever fashion you see fit :-)

Categories