Php-fpm still logging my error even when using catch - php

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.

Related

How to continue PHP loop if you get a Warning?

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

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);
}

Is there a clean way to parse wordpress logs?

I am doing a plugin that checks log errors every day and send them by UDP.
My idea was to open debug.log and check line by line if the error is anterior to the last time I checked them, and then I check if it's a critical error or a warning.
That is pretty easy, but problem is an error can do more than one line!
And there is a stack trace some times (well, I could just skip it because it's always begins with #).
This is my code actually but it doesn't work when an error have multiple lines.
$path = fs_get_wp_config_path();
$path = $path . "/wp-content/debug.log";
$logs = file($path);
$date = get_option('last_date');
if ($date == false)
{
add_option('last_date', '27-Aug-2015 09:43:55 UTC');
$date = get_option('last_date');
}
$last_date = new DateTime("27-Aug-2015 09:43:55 UTC");
for($i = 0; $i < count($logs); $i++)
{
var_dump($logs[$i]);
if (substr($logs[$i], 0, 12) == "Stack trace:")
{
$i++;
while (substr($logs[$i], 0, 1) == '#' && $i < count($logs))
$i++;
$i++;
}
else
{
$log_date = substr($logs[$i], 1, 24);
$new_date = new DateTime($log_date);
//var_dump ($new_date);
}
}
Do you know how can I do that ?
Thanks
EDIT : This is a sample of my log file
[27-Aug-2015 12:49:14 UTC] PHP Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): \
Failed to parse time string (tack trace:
) at position 0 (t): The timezone could not be found in the database' in /Users/opsone/Sites/wordpress/wp-content/p\
lugins/opsonemonitoring/log.php:51
Stack trace:
#0 /Users/opsone/Sites/wordpress/wp-content/plugins/opsonemonitoring/log.php(51): DateTime->__construct('tack trace\
:\n')
#1 /Users/opsone/Sites/wordpress/wp-content/plugins/opsonemonitoring/opsonemonitoring.php(30): get_log()
#2 /Users/opsone/Sites/wordpress/wp-content/plugins/opsonemonitoring/opsonemonitoring.php(142): opsoneMonitoring()
#3 [internal function]: mysettings_page('')
#4 /Users/opsone/Sites/wordpress/wp-includes/plugin.php(496): call_user_func_array('mysettings_page', Array)
#5 /Users/opsone/Sites/wordpress/wp-admin/admin.php(212): do_action('settings_page_m...')
#6 /Users/opsone/Sites/wordpress/wp-admin/options-general.php(10): require_once('/Users/opsone/S...')
#7 {main}
thrown in /Users/opsone/Sites/wordpress/wp-content/plugins/opsonemonitoring/log.php on line 51
[27-Aug-2015 12:52:04 UTC] PHP Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): \
Failed to parse time string (tack trace:
) at position 0 (t): The timezone could not be found in the database' in /Users/opsone/Sites/wordpress/wp-content/p\
lugins/opsonemonitoring/log.php:51
Stack trace:

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.

How to resolve the com_exception error in php which occurs in reload (reading barcodes from images)?

I am using clear image SDK for reading barcode from images. The code is working only first time on my browser. When I reload the page, it throws an exception. To make it work again, I restart my web server and it works again. But when I reload the page, it again throws the same exception. The error is given below:
( ! ) Fatal error: Uncaught exception 'com_exception' with message '<b>Source:</b> ClearImage.ClearImage.1<br/><b>Description:</b> SEH Exception 0xC0000005' in C:\wamp\www\test.php on line 11
( ! ) com_exception: <b>Source:</b> ClearImage.ClearImage.1<br/><b>Description:</b> SEH Exception 0xC0000005 in C:\wamp\www\test.php on line 11
If I call the script from command line, it works fine and it does not matter if I call the script again. I dont need to restart the webserver at all.
What is exactly going on with this script? Do I need to close any particular resources or connections in the script so that it can work again? This is the first time I am working with COM object.
<?php
try {
// To insert line breaks in HTML output replace \n with <br>
// Create and Configure ClearImage Object
$Ci = new COM("ClearImage.ClearImage");
} catch (Exception $e) {
echo $e->getMessage();
}
// Create the 1D Barcode Pro object. Use any of the other engines here.
$Bc = $Ci->CreateBarcodePro();
// Open file.
$File = 'c39.tif'; // Use YOUR file name
$File = 'C:\\test.jpg';
$Bc->Image->Open($File);
// $Bc->Code39 = true;
// Set reading parameters. Update values if needed. See Online API help
$Bc->AutoDetect1D = 65535;
/*
* my testing
*/
$Bc->Type = 2;
$Bc->Directions = 2;
$Bc->Algorithm = 2;
/*
* my tesing
*/
$Bc->Algorithm = 2;
// Read Barcodes
$BCcount = $Bc->Find(0);
echo "\nBarcodes: $BCcount\n";
if ($BCcount == 0) {
$Msg = "No barcodes found in $File \n";
exit($Msg);
}
for ($i = 1; $i <= $BCcount; $i ++) {
echo "Barcode #$i ";
$FBc = $Bc->BarCodes($i);
// NOTE: Text value will terminate on the first null in data
echo "Type: $FBc->Type Length: $FBc->Length\n";
echo "Barcode Value: $FBc->Text \n";
echo " Binary Data in Hex: \n ";
$hex_ary = array();
$cnt = 0;
foreach ($FBc->Data as $chr) {
$hex_ary[] = sprintf("%02X", $chr);
$cnt = $cnt + 1;
if ($cnt == 16) // break lines after 16 numbers
{
$hex_ary[] = sprintf("\n");
$cnt = 0;
}
}
echo implode(' ', $hex_ary);
echo "\n";
}
unset($Ci);

Categories