I have code that I am trying to update to work with at least PHP version 7.3 and even when I put in a try catch statement I still get a fatal error thrown.
Below is the function that puts Objects into the Session. line causing error: $objects[$i] = $Object;
function findObjectsLIB() {
$objects = ""; $i = 0;
foreach ($_SESSION['Objects'] as $o => $Object) {
$className = get_class($Object);
if (!empty($className)) {
try {
$objects[$i] = $Object;
$i++;
} catch(Exception $err) {
$_SESSION['errors'] .= $err->getMessage();
}
}
}
return $objects;
}
I am getting this error.
PHP Recoverable fatal error: Object of class Extra could not be
converted to string.
How it not being caught?
For one it is strange that it is not being caught and why is it having an issue in 7.3 but not 5.6?
I want to receive the error message in php before it gets executed. Basicly what i mean is that if I would have a bad code:
// This code is incorrect, I want to receive the error before it gets handled!
$some_var = new this_class_is_not_made;
Now that class does not exist, so it would be handles by the default error handler in php. But I want to disable the normal error handler and create my own.
Another example:
somefunction( string some_var ); // some_var misses the variable prefix. ( $ )
Example error message:
Fatal error: function 'some_var' is not defined in line: $x!
And this error would be: somefunction( string some_var );
But how would I receive the messages but also disable the normal error system?
EDIT: Making the error system execute a user-defined function
// I would want the error system to execute a function like this:
function(string $errorMessage, int $error_code){
if($error_code < 253){ return "Fatal error"; }
if($error_code < 528 && $error_code > 253){ return "Warning"; }
}
Answer found: By: ShiraNai7
try
{
// Code that may throw an Exception or Error.
}
catch (Throwable $t)
{
// Executed only in PHP 7, will not match in PHP 5
}
catch (Exception $e)
{
// Executed only in PHP 5, will not be reached in PHP 7
}
In PHP 7.0.0 or newer the code will throw Error exception if this_class_is_not_made doesn't exist.
try {
$some_var = new this_class_is_not_made;
} catch (Error $e) {
echo $e->getMessage();
}
Note that that this will also catch any other Error exceptions in case this_class_is_not_made does exist and causes some other error along the way.
In PHP versions prior to 7.0.0 you're out of luck - fatal errors always terminate the main script.
It might be a better idea to use class_exists() instead:
if (class_exists('this_class_is_not_made')) {
$some_var = new this_class_is_not_made;
}
This works in all PHP versions that support classes.
I would like to ask can I require/include a file that has syntax errors and if I cant, the require/include returns a value so that I know that the required/included file has syntax errors and cannot be required/included ?
file.php has syntax error
include('file.php')
if (not file.php included because of syntax)
this
else
that
If you really wanted this type of functionality.
You could try using nikics php parser to see if you can successfully parse the file or not.
$code = file_get_contents('yourFile.php');
$parser = new PhpParser\Parser(new PhpParser\Lexer\Emulative);
try {
$stmts = $parser->parse($code);
// $stmts is an array of statement nodes
// file can be successfully included!
} catch (PhpParser\Error $e) {
// cannot parse file!
echo 'Parse Error: ', $e->getMessage();
}
In PHP 7, Parsing errors can be caught, which makes this probably the most robust, elegant, built-in solution:
<?php
function safe_require_once(string $fname) {
try {
require_once($fname);
} catch( Throwable $e ) {
//will throw a warning, continuing execution...
trigger_error("safe_require_once() error '$e'", E_USER_WARNING);
}
}
safe_require_once("./test1.php"); //file with parse or runtime errors
echo "COMPLETED SUCCESSFULLY THO";
you can use something ike this:
if((#include $filename) === false)
{
// handle error
} else { //....}
the # is used to hide the error message
If I include a file in to php. If there is any fatal error in that php then is there any way to skip that .
<?php
include "somefile.php";
echo "OK"; // Is there any way to print this OK If there is any fatal error on somefile.php
?>
I need to include this somefile.php file. It may return fatal error
for some host. I want to skip this file for those host.
Please Advice me.
With this, you can define your own continuation function that will take over in case of a fatal error. This uses register_shutdown_function() to intercept the fatal error.
Usage:
function my_continuation_func($filename, $arg2) {
// On fatal error during include, continue script execution from here.
// When this function ends, or if another fatal error occurs,
// the execution will stop.
}
include_try('my_continuation_func', array($filename, $arg2));
$data = include($filename);
$error = include_catch();
If a fatal error occurs (like a parse error), script execution will continue from my_continuation_func(). Otherwise, include_catch() returns true if there was an error during parsing.
Any output (like echo 'something';) from the include() is treated as an error. Unless you enabled output by passing true as the third argument to include_try().
This code automatically takes care of possible working directory changes in the shutdown function.
You can use this for any number of includes, but the second fatal error that occurs cannot be intercepted: the execution will stop.
Functions to be included:
function include_try($cont_func, $cont_param_arr, $output = false) {
// Setup shutdown function:
static $run = 0;
if($run++ === 0) register_shutdown_function('include_shutdown_handler');
// If output is not allowed, capture it:
if(!$output) ob_start();
// Reset error_get_last():
#user_error('error_get_last mark');
// Enable shutdown handler and store parameters:
$params = array($cont_func, $cont_param_arr, $output, getcwd())
$GLOBALS['_include_shutdown_handler'] = $params;
}
function include_catch() {
$error_get_last = error_get_last();
$output = $GLOBALS['_include_shutdown_handler'][2];
// Disable shutdown handler:
$GLOBALS['_include_shutdown_handler'] = NULL;
// Check unauthorized outputs or if an error occured:
return ($output ? false : ob_get_clean() !== '')
|| $error_get_last['message'] !== 'error_get_last mark';
}
function include_shutdown_handler() {
$func = $GLOBALS['_include_shutdown_handler'];
if($func !== NULL) {
// Cleanup:
include_catch();
// Fix potentially wrong working directory:
chdir($func[3]);
// Call continuation function:
call_user_func_array($func[0], $func[1]);
}
}
Fatal means fatal ...
There is no way to recover from a fatal error.
You can use register_shutdown_function.
<?php
function echoOk()
{
echo "OK";
}
register_shutdown_function(function ()
{
$error = error_get_last();
// to make sure that there is any fatal error
if (isset($error) &&
($error['type'] == E_ERROR
|| $error['type'] == E_PARSE
|| $error['type'] == E_COMPILE_ERROR
|| $error['type'] == E_CORE_ERROR))
{
echoOk();
}
});
include "somefile.php";
echoOk();
But you can do it only once. Any further fatal error will stop execution.
PHP won't tolerate with Fatal Errors. Best to check the included file and solve it.
Actually, you can try looking at register-shutdown-function, but it's not recommended to run away from your problems.
Yes, there is. It can be done through a simple if statement
You Have:
<?php
include "somefile.php";
echo "OK"; // Is there any way to print this OK If there is any fatal error on
?>
Try This:
<?php
if(include "somefile.php"){
// echo do something if success
}else{
echo "OK";
}
edit: I missed the word fatal. As stated, you can't recover from a fatal error. If it is just an exception the hastly writen response below will work.
Including another php module is the same as that code being inserted inline, so a simple try-catch statement should work:
<?php
try {
include "somefile.php";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
echo "OK";
?>
Try to set a set_error_handler() function that doesn't die on fatal errors, but instead Apache crashed. In other words, PHP needs to die so that the system doesn't.
See this LINK
Fatal Error means there is something seriously wrong with the including code. As #Orangepill said there is no way to stop this fatal error message popping up. Please go through your coding and find the error.
<?php
try {
$attrs = $xml->attributes();
$code = $attrs['_Code'];
}
catch (Exception $e)
{
$code = '';
}
?>
Gets me:
Fatal error: Call to a member function attributes() on a non-object on
line 6
Why am I getting errors thrown on code wrapped in a try-catch??
NOTE: It is possible to avoid this error by using the following code. (The question is not about avoiding the error, but why it's not being caught- still I thought I'd share the non-erroring code anyway)
if (is_object($xml) && method_exists($xml,'attributes')) {
$attrs = $xml->attributes();
$code = !empty($attrs['_Code'])?$attrs['_Code']:'';
}
else {
$code = '';
}
PHP fatal errors cannot be caught. I don't know the specifics of what you're doing, but you'll have to figure out some other way to test whether $xml->attributes() will work or not.
Also, swallowing every error and not logging it anywhere is bad practice because when stuff starts breaking you won't have any idea of why.
try/catch only works for exceptions, not parse errors. You have to test to make sure that $xml has an attributes method to avoid such an error (could be called a null pointer, but not exactly).