Execute a function on error php - php

Once i initiated a function i am setting a flag on DB to TRUE.
and i need to set it FALSE on the end of the function.
Ex:
Class Preprocessor extends Machine{
function process(){
$this->db->setValue(TRUE); //Setting DB flag to TRUE
//OTHER CODES
$this->close_db_value(); // Setting DB flag to FALSE
}
function close_db_value(){
$this->db->setValue(FALSE); //Setting DB flag to FALSE
}
}
As you can see that it will work in normal cases, But if some error encountered in //OTHER CODES section then it will not execute the rest of codes.
The function mainly work in background (But not as a command line,its just closing the connection and start executing on background).
How can i ensure that the close_db_value() function executed upon script termination ?
Some of possibilities
Some critical errors that which leads the script to termination
exit called somewhere on the //OTHER CODE section
PHP max_execution_time exceeded
A Force Kill
Please help.

Use the set_error_handler() function in PHP. Place the name of the callback function you want called in case of error as the first parameter. Put the level of error (optional) that you want as the trigger as the second parameter.
If you are looking to handle every other type of error (except SIGKILLs or force quits), you can also try using register_shutdown_function() with a error_get_last() and a switch-case statement with the various types of errors you wish to handle (E_NOTICE, E_DEPRECATED, etc.).
For example,
register_shutdown_function('shutdown_callback');
function shutdown_callback(){
$error_type = error_get_last();
switch($error_type){
case E_ERROR: break;
case E_WARNING: break;
}
}

The __destruct(); magic function will also execute every time the script ends, or an object is unloaded.

Related

How to count concurrent instances of a running function using PHP and MySQL? [duplicate]

Once i initiated a function i am setting a flag on DB to TRUE.
and i need to set it FALSE on the end of the function.
Ex:
Class Preprocessor extends Machine{
function process(){
$this->db->setValue(TRUE); //Setting DB flag to TRUE
//OTHER CODES
$this->close_db_value(); // Setting DB flag to FALSE
}
function close_db_value(){
$this->db->setValue(FALSE); //Setting DB flag to FALSE
}
}
As you can see that it will work in normal cases, But if some error encountered in //OTHER CODES section then it will not execute the rest of codes.
The function mainly work in background (But not as a command line,its just closing the connection and start executing on background).
How can i ensure that the close_db_value() function executed upon script termination ?
Some of possibilities
Some critical errors that which leads the script to termination
exit called somewhere on the //OTHER CODE section
PHP max_execution_time exceeded
A Force Kill
Please help.
Use the set_error_handler() function in PHP. Place the name of the callback function you want called in case of error as the first parameter. Put the level of error (optional) that you want as the trigger as the second parameter.
If you are looking to handle every other type of error (except SIGKILLs or force quits), you can also try using register_shutdown_function() with a error_get_last() and a switch-case statement with the various types of errors you wish to handle (E_NOTICE, E_DEPRECATED, etc.).
For example,
register_shutdown_function('shutdown_callback');
function shutdown_callback(){
$error_type = error_get_last();
switch($error_type){
case E_ERROR: break;
case E_WARNING: break;
}
}
The __destruct(); magic function will also execute every time the script ends, or an object is unloaded.

PHP: need some clarification about custom error and exception handlers and trigger_error

Question #1:
I have a custom error_handler to be registered by set_error_handler(). If I intercept E_USER_ERROR inside it should I call die() or exit() manually to end the script or it will be done automatically by PHP.
Question #2:
I have a custom exception_handler to be registered by set_exception_handler(). Should I call die() or exit() manually to end the script or it will be done automatically by PHP.
Question #3:
If i have error_reporting(0) does it mean that my trigger_error() calls will not trigger errors
Have you checked the manual? :)
1.) http://php.net/set-error-handler
Also note that it is your responsibility to die() if necessary. If the error-handler function returns, script execution will continue with the next statement after the one that caused an error.
2.) http://php.net/set-exception-handler
Execution will stop after the exception_handler is called.
3.) http://php.net/trigger-error
Generates a user-level error/warning/notice message.
This will obey your error_reporting setting for E_USER_NOTICE's unless a second parameter is used.

Proper way to 'exit' a script in PHP

I have a static method named ServerResponse that basically shows a message whether on success or fail. I just want to know the proper way to actually display the message and exit the script.
Should I implement my method like this:
public static function ServerResponse($e,$m){
print(json_encode([$e,$m]));
exit;
}
//Sample use:
if(this happens){
myclass::ServerResponse($x,$y);
}
or like this:
public static function ServerResponse($e,$m){
return json_encode([$e,$m]);
}
//Sample use:
if(this happens){
print(myclass::ServerResponse($x,$y));
exit;
}
Which one is proper and better... and why?
is there any difference between them? (on execution time).
"Don't be hard on me I am not an expert (just yet)..."
For better debugging, it's advised to always make a function or method return a value. So your 2nd sample should be chosen.
exit (or die) are commonly used when the program ends with an error, giving the ability to add an exit status (as a number or a string).
I suppose there will be no significant difference about the execution time.
I don't know if this is common practice but I only use exit to debug. If your script comes to the end of execution it will exit on it's own.
If you must exit, do it in the main script, not in a function.
functions should have one task and do that task. So the function ServerResponse should send a response and not kill the script.

php ErrorHandler - Error Count

As you probably already know, the error handler in php can be replaced by a function using
set_error_handler()
I'm making my own error handler, and I want to do something when I have gotten all of the errors.
As of right now, the custom error handling function will be executed every time an error occurs.
So, what a way to know if it's the last error, so I can execute a html script.
I suspect you are looking for register_shutdown_function():
Registers a callback to be executed after script execution finishes or
exit() is called.
But you'd better assure that your callback function does not trigger any error xD
If you want to handle all the errors in one go (which means you will lose visibility of errors occuring before a fatal error - hence I do not recomend this) then register a sutdown function and just accumulate the data via your error handler then in your shutdown function report the errors....
<?php
$mylog="started\n"
function logit() {
global $mylog;
if ($mylog) {
file_put_contents(tmpnam('/var/log/php', 'err');
}
}
register_shutdown_function('logit');
function whoops()
{
global $mylog;
$mylog.="something bad happenned\n";
}
set_error_handler('whoops');
....
(this can all be done with an auto-prepend file)

Cheking and error on a PHP function

There is a way to check with a "IF" if a function fails in php?
Ex.
If (getimagesize($image) returns and error) {
echo 'Error: function dont work';
}
else
{
// do something
}
Thanks!
I 'm assuming you are interested specifically in a function like getimagesize, which does not return any error codes and makes it hard on us. But not impossible.
The documentation for getimagesize states:
If accessing the filename image is impossible, or if it isn't a valid picture, getimagesize() will generate an error of level E_WARNING. On read error, getimagesize() will generate an error of level E_NOTICE.
Therefore, you need to do two things:
Get notified of the error and act upon it somehow
Have the error not be displayed or otherwise affect the execution of your program at all (after all, your are going to be taking care of any errors with error-handling code yourself)
You can achieve the first one using set_error_handler() and restore_error_handler(). You can achieve the second with the error-control operator #.
So, the code must go something like this:
// Set our own error handler; we will restore the default one afterwards.
// Our new error handler need only handle E_WARNING and E_NOTICE, as per
// the documentation of getimagesize().
set_error_handler("my_error_handler", E_WARNING | E_NOTICE);
// No error has occured yet; it is the responsibility of my_error_handler
// to set $error_occurred to true if an error occurs.
$error_occurred = false;
// Call getimagesize; use operator # to have errors not be generated
// However, your error handler WILL STILL BE CALLED, as the documentation
// for set_error_handler() states.
$size = #getimagesize(...);
// At this point, my_error_handler will have run if an error occurred, and
// $error_occurred will be true. Before doing anything with it, restore the
// previous error handler
restore_error_handler();
if($error_occurred) {
// whatever
}
else {
// no error; $size holds information we can use
}
function my_error_handler($errno, $errstr, $file, $line) {
global $error_occurred;
// If the code is written as above, then we KNOW that an error
// here was caused by getimagesize(). We also know what error it was:
switch($errno) {
case E_WARNING: // Access to image impossible, or not a valid picture
case E_NOTICE: // Read error
}
// We could also check what $file is and maybe do something based on that,
// if this error handler is used from multiple places. However, I would not
// recommend that. If you need more functionality, just package all of this
// into a class and use the objects of that class to store more state.
$error_occurred = true;
return true; // Do not let PHP's default error handler handle this after us
}
Of course, this is not very maintainable (you have a global variable $error_occurred there, and this is not a good practice). So for a solution which not only works but is also nicely engineered, you would package all this in a class. That class would define:
A method which implements the error handler (my_error_handler in the above example). To set an object method as an error handler instead of a global function, you need to call set_error_handler with a suitable first parameter; see the documentation for callback.
A method which lets the class set the error handler, execute some code of your choice, save the "error happened while executing your code" flag, and restore the error handler. This method could e.g. take a callback provided by your calling code and an array of parameters and use call_user_func_array to execute it. If, during execution, the error handler set from #1 above is called, mark this in a variable in your object. Your method would return the return value of call_user_func_array to the calling code.
A method or variable which the calling code can use to access the result from #2 above.
So then, if that class is called ErrorWatcher, your calling code would be something like:
$watcher = new ErrorWatcher;
$size = $watcher->watch("getimagesize",
array( /* params for getimagesize here */ ));
// $size holds your result, if an error did not occur;
// check for errors and we 're done!
switch($watcher->report_last_error()) {
// error handling logic here
}
...which is nice and neat and does not mess with global variables. I hope I explained this well enough to enable you to write class ErrorWatcher yourself. :-)
Take a look at exceptions. You'll have to throw them in your function though.
Edit: By the way, if your function is not supposed to return a boolean, you can always have it return false if something goes wrong and check like:
$result = getimagesize($image);
if ($result === false)
{
//
}
Whatever the condition is on an "if" statement (what's inside the parenthesis) will return "true" or "false".
If the condition returns "true", the first statement will be executed, otherwise the second statement will get executed.
You can put this, error_reporting(E_ALL); at the very top of your script, right after your opening php tag, to see what error you get.
Hope it helps.
Maybe something like this:
<?php
error_reporting(E_ALL);
more stuff here ...
if(your condition here){
echo "condition is true, do something";
}else{
echo "condition is not true, do something else";
}
if the function or statement you run inside the "if" or "else" fails, at least you know which one was it based on the result, and the error_reporting might tell you why it failed.

Categories