Could someone help me translate this code to PHP 4?
try
{
$picture = PDF_open_image_file($PDF, "jpeg", $imgFile, "", 0); // This is the original statement, this works on PHP4
}
catch(Exception $ex)
{
$msg = "Error opening $imgFile for Product $row['Identifier']";
throw new Exception($msg);
}
Basically when there is a fatal error I need to get the $row['Identifier'] so I know what product is causing the error.
Thanks in advance.
EDIT: I don't know what PHP_open_image_file does, but sometimes I get errors like below, and I need to get the product identifier that is causing the error.
Fatal error: PDFlib error [1016]
PDF_open_image_file: Couldn't open
JPEG file 'picture/b01_le1x.jpg' for
reading (file not found) in
/var/www/html/catalogue/pdf_make.php
on line 618
Am I correct in assuming you are using PDF_open_image_file() from the pdflib PECL extension?
If so, then it will never throw an exception on PHP 4. I would assume error states are reported through the result, which is an int and thus probably < 1 in case of errors.
//try
if (file_exists($imgFile)) {
$picture = PDF_open_image_file($PDF, "jpeg", $imgFile, "", 0);
}
//catch
if (!$picture) {
$msg = "Error opening $imgFile for Product $row['Identifier']";
print $msg;
}
I've updated this with file_exists to prevent your fatal error.
As addendum question, why were you trying to rethrow an exception on PHP4?
You can catch some problems by setting a default error handler (see PHP Manual entry), but that won't let you catch E_ERRORS.
I don't think this will be possible in PHP4, you'll need to upgrade to PHP5 so it throws an exception instead of an E_ERROR. You may be able to catch certain errors before they happen - for example by running file_exists() on your input file, but you are unlikely to be able to think of and catch all the errors that PDFLib will.
Related
I am using the PHP copy function in part of my program, where the parameters of the function depend on user input. I am trying to avoid the default php error message if they include a path that the function cannot use, and output a custom message like shown below. I am new to handling errors/ exceptions. I am still getting the php default error message instead of the custom 'Path was incorrect!' using the method below.
What I tried:
try{
copy($webImagePath, $destinationPath);
}
catch(Exception $e){
echo 'Path was incorrect!';
}
Consider set_error_handler: http://php.net/manual/en/function.set-error-handler.php
Example:
set_error_handler("someFunction");
function someFunction($errno, $errstr) {
output details and information
}
You should have thrown an Exception with custom message you wished to display.
You can either suppress the default PHP error message for individual statements by preceding them with an '#' symbol. Or you might change error_reporting level per page( check this link for more details:http://php.net/manual/en/function.error-reporting.php
Also check the folowing code snippet
$file='example.txt'; //replace the file name with your URL
$newfile = 'example.txt.bak';
try{
$ret=#copy($file, $newfile);
if (!$ret){
throw new Exception("File path doesn't exist..");
}
}
catch(Exception $e){
echo $e->getMessage();
}
getimagesize giving error Filename cannot be empty PHP 8
if(isset($_FILES["nuevaFoto"]["tmp_name"])) {
list($ancho, $alto) = getimagesize($_FILES["nuevaFoto"]["tmp_name"]);
}
I do not get this error under PHP 7.3. But in PHP 8.0 the error is thrown during the file upload.
This is due to the error re-classification made for PHP8.
I advise you to check for an empty string too in your condition
<?php
if(isset($_FILES["nuevaFoto"]["tmp_name"]) && $_FILES["nuevaFoto"]["tmp_name"] !== ''){
list($ancho, $alto) = getimagesize($_FILES["nuevaFoto"]["tmp_name"]);
}
Alternatively you could catch (ValueError $e) but this error is pretty generic so this is not advised.
For the record you yan check the output for various PHP versions with this link: https://3v4l.org/HgXpT
The change has been made in this Pull Request https://github.com/php/php-src/pull/5902
I am unable to execute a code inside catch block when there is a file exception. Below is the code.
try {
// Check for file size. which will make sure file exists in local server.
filesize($localPath);
return 'success';
}catch(FileException $e) {
Log::error('Error reading file size ' . $e->getMessage());
$failedAttempts = $failedAttempts + 1;
// Set to sleep for 10.
sleep(10);
// Start recursive call.
$this->downloadMedia($url, $localPath, $failedAttempts);
}
I also tried \Exception and \ErrorException but nothing worked. Any help is appreciated.
if You check this manual You'll see filesize method does not throw exception.
Returns the size of the file in bytes, or FALSE
(and generates an error of level E_WARNING) in case of an error.
and since looks like You've not enabled error reporting or display_error directive - You don't see that E_WARNING
You can just throw exception manually:
try {
// Check for file existence or throw exception.
if (!is_file($localPath)) {
throw new Exception($localPath.' does not exists');
}
return 'success';
}
catch(Exception $e) {
// here goes exception handling
}
Extra advice (out of question's scope):
There is no logic to check for file existence in recurring way.
If file is downloaded it will exist otherwise You'll never download it during recursion.
What if someone will pass link to file that does not exists?
Better jus download it and stop with success or exception.
I've read this thread: php: catch exception and continue execution, is it possible?
Every answer suggests that a try catch will continue executing the script. Here is an example where it doesn't:
try{ $load = #sys_getloadavg(); }
catch (Exception $e){ echo 'Couldn\'t find load average.<br>'; return false; }
I'm running it on xampp on windows, which could be why it errors (it gives a Call to undefined function sys_getloadavg() error when the # is removed), but that isn't the issue in question. It could be any function that doesn't exist, isn't supported or fails - I can not get the script to continue executing.
Another example is if there is a syntax error in the try, say I'm including an external file and parsing it as an array. This also produces an error and stops executing.
Is there any brute force way to continue the script running, regardless of what fails in the try?
Unlike other languages, there's a difference in PHP between exceptions and errors. This would be like a compile error in other languages. that require declaration files. You can't catch or ignore Fatal errors like a function not exisiting. You can test for existence before using though:
if( function_exists('sys_getloadavg') {
try{ $load = #sys_getloadavg(); }
catch (Exception $e){ echo 'Couldn\'t find load average.<br>'; return false; }
}
Why am I getting this error?
Warning: file_get_contents(http://www.example.com) [function.file-get-contents]: failed to open stream: HTTP request failed! in C:\xampp\htdocs\test.php on line 22
Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\test.php on line 22
Here is the code:
try {
$sgs = file_get_contents("http://www.example.com");
}
catch (Exception $e) {
echo '123';
}
echo '467';
Aren't try\catch supposed to continue the excecution of the code? Or maybe there is some different way to do it?
try... catch is more for null object exceptions and manually thrown exceptions. It really isn't the same paradigm as you might see in Java. Warnings are almost deceptive in the fact that they will specifically ignore try...catch blocks.
To suppress a warning, prefix the method call (or array access) with an #.
$a = array();
$b = #$a[ 1 ]; // array key does not exist, but there is no error.
$foo = #file_get_contents( "http://somewhere.com" );
if( FALSE === $foo ){
// you may want to read on === there;s a lot to cover here.
// read has failed.
}
Oh, and it is best to view Fatal Exceptions are also completely uncatchable. Some of them can be caught in some circumstances, but really, you want to fix fatal errors, you don't want to handle them.
catch cannot catch a fatal error.
Just search for timeout in the manual for file_get_contents, there are several solutions listed there, here is one:
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 1
)
)
);
file_get_contents("http://example.com/", 0, $ctx);
try..catch will only catch exceptions. A fatal error is not an exception.
If PHP exceeds its maximum execution time, there's nothing you can do. PHP simply stops dead. It's the same if PHP runs out of memory: Nothing you can do to fix it after it's happened.
In other words, exceptions are errors you can potentially recover from. Fatal errors are, well, fatal and unrecoverable.
In PHP a fatal error will halt execution of the script. There are ways to do something when you run into them, but the idea of a fatal error is that it should not be caught.
Here are some good details: http://pc-technic.blogspot.com/2010/10/php-filegetcontents-exception-handling.html
Basically change your code to do the following:
try {
#$sgs = file_get_contents("http://www.example.com");
if ($sgs == FALSE)
{
// throw the exception or just deal with it
}
} catch (Exception $e) {
echo '123';
}
echo '467';
Note the use of the '#' symbol. This tells PHP to ignore errors raised by that particular piece of code. Exception handling in PHP is very different than java/c# due to the "after the fact" nature of it.
Fatal errors in PHP are not caught. Error handling and Exception handling are two different things. However if you are hell bent on handling fatal errors as exception, you will need to set up your own error handler and direct all errors to it, make your error handler throw exceptions and you can then catch them.
file_get_contents doesn't throw exception (and thus errors and warnings it throws aren't catchable). You are getting PHP warning and then fatal error, which explains you why the script doesn't continue - it exceeded limit for loading scripts set in php.ini.