how to properly manage triggered errors in PHP4 - php

m maintaining a project, that has to be compatible through PHP 4.X to 5.2. The project as several errors wich are not very well handled.
What I want to do is redirect user to a "nice" error page, and log the error in the database. In order to keep track of the user, the file, and the error message. Here is what I've tried so far:
set_error_handler("myErrorHandler");
/**
*My function to handle errors
*/
function myErrorHandler( $errno , $errstr , $errfile="nofile" , $errline=0 , $errcontextArray=NULL ){
session_start();
if (!isset($errno)|!isset($errstr)) {
exit(0);
}
if (!mysql_ping()) {
require '../Connection/databaseinfo.php';
}
$id_user = $_SESSION['ident'];
$errstr = GetSQLValueString($errstr, "text");
$errfile = GetSQLValueString($errfile, "text");
$errline = GetSQLValueString($errline, "int");
$sql = "insert into error_history
(id_user, message, file, line)
values ($id_user, $errstr, $errfile, $errline)";
mysql_query($sql) or die (mysql_error());
// header("location:error.php"); ---> I can't (see comment below)
echo "<script type='text/javascript'> window.location.href='error.php';</script>";//Redirection dégueulasse //TODO: trouver mieux
return true;
}
Why not header()? Because the error can be triggered anywhere in a page, and thus, having the headers already sent.
Why not header() along with obstart(), ob_flush()? Because there are lot of pages already in production, and I can't modify them all.
My questions are:
Am I doing it wrong?
Is there a better way to handle the
redirection?

This is how to handle fatal errors in php 5.2:
<?php
register_shutdown_function('shutdownFunction');
function shutDownFunction() {
$error = error_get_last();
if($error['type'] >= 1){
mail('cc#cc.de', 'Error: XY',"Error msg:"."Server Error:".implode("\n", $error));
}
}
?>

Related

PHP sending message via TCP/IP

Im try to send a Message from PHP Website via TCP/IP to an Arduino.
With following code i'm able to send a message from php website
<?php
$errno = NULL;
$error = NULL;
if (!$handle = #fsockopen("192.168.188.24", "49419", $errno, $error, 10))
{
die("Fehler (".$errno."): ".$error);
}
fwrite($handle, "ON\r\n");
fclose($handle);
?>
The problem is, when calling the website for the first time, the message doesnt get delivered immediatly. Just after some refreshes of the website, the message arrives, but logical so many times like amount of website refreshes.
Already tried to limit the messagelength to 2bytes, but without any success.
Try adding inside a try - catch block.
try {
} catch (Exception $e) {
echo $e->getMessage();
}
To see what exception you may get.

PHP custom error handler reporting 0 in on line 0

I have a custom error handler that's supposed to log errors to a database, but for some reason this error always shows up in the database. Every time a page is loaded "0 in on line 0", where the first 0 is the error level, in whatever file, since it's not provided, on line 0. This is odd because I've never seen this until now. The error handler is below;
public function fatalErrHandlr(){
$errstrArr = error_get_last();
$errno = mysqli_real_escape_string($this->dbc, trim($errstrArr['type']));
$errstr = mysqli_real_escape_string($this->dbc, trim($errstrArr['message']));
$errfile = mysqli_real_escape_string($this->dbc, trim($errstrArr['file']));
$errline = mysqli_real_escape_string($this->dbc, trim($errstrArr['line']));
$query = "INSERT INTO `err` (`errno`, `errstr`, `errfile`, `errline`) VALUES ('$errno', '$errstr', '$errfile', '$errline')";
mysqli_query($this->dbc, $query);
//var_dump(mysqli_error($this->dbc));
echo("<b>There was an error. Check the database.</b>");
//return true;
}
The error handler is configured with:
register_shutdown_function(array($core, 'fatalErrHandlr'));
register_shutdown_function doesn't configure an error handler, it sets a function to run whenever the script finishes. So you're getting a log message every time the script runs, whether or not it got an error. The correction function is set_error_handler. It passes the details as arguments to the callback, so you don't need to use error_get_last
public function fatalErrHandlr($errno, $errstr, $errfile, $errline){
$query = $this->dbc->prepare("INSERT INTO `err` (`errno`, `errstr`, `errfile`, `errline`) VALUES (?, ?, ?, ?)");
$query->bind_param('ssss', $errno, $errstr, $errfile, $errline)
$query->execute();
//var_dump(mysqli_error($this->dbc));
echo("<b>There was an error. Check the database.</b>");
//return true;
}

PHP error is visible in production in shared hosting

I am getting the below error in one of the file in Production, where the function is defined twice. I tried to recreate the issue, getting in a different file.
Fatal error: Cannot redeclare foo() (previously declared in
/home/content/45/8989001/html/test/test.php:5) in
/home/content/45/8989001/html/test/test.php on line 10
To suppress this error, its advised to make an entry to php.ini file, but I don't have access to it as its shared hosting.
Alternatively, its suggested to make an entry to existing php file inside the <?php ?> tags. I did the below change.
error_reporting(0); // This is not working, still error is displayed
error_reporting(E_NONE); // This is not working, still error is displayed
ini_set('display_errors', 0); // This is not working, still error is displayed
My complete code,
<?php
function foo() {
return "foo";
}
function foo() {
return "foo";
}
// error_reporting(0); // This is not working, still error is displayed
// error_reporting(E_NONE); // This is not working, still error is displayed
ini_set ( 'display_errors', 0 ); // This is not working, still error is displayed
echo "hello";
?>
Problem: How to suppress this error in Production, instead log to some file. or at-least suppress the error?
Note: The error is fixed in prod, but how to suppress it to avoid user seeing error in some other file next time
Update1:
After the below change too, the error is the same.
<?php
ini_set ( 'display_errors', 0 );
function foo() {
return "foo";
}
function foo() {
return "foo";
}
// error_reporting(0); // This is not working, still error is displayed
// error_reporting(E_NONE); // This is not working, still error is displayed
// ini_set ( 'display_errors', 0 ); // This is not working, still error is displayed
echo "hello";
?>
Update2:
<?php
register_shutdown_function( "fatal_handler" );
function fatal_handler() {
echo "inside fatal_handler";
$errfile = "test";
$errstr = "shutdown this test";
$errno = E_CORE_ERROR;
$errline = 0;
$error = error_get_last();
echo $error;
if( $error !== NULL) {
$errno = $error["type"];
$errfile = $error["file"];
$errline = $error["line"];
$errstr = $error["message"];
$newline = "\r\n";
define ( 'senderName', 'Error' );
define ( 'senderEmail', 'admin#abc.com' );
$headers = "From: " . senderName . " <" . senderEmail . "\r\n";
$subject_admin = 'Error-Fix it';
$body_admin = "Dear Admin, $newline$newline An error occured $newline" . "error number : " . $errno . $newline . " error file : $errfile" . $newline . "error line :" . $errline . $newline . "error string : $errstr" . $newline;
$body_footer = " **** This is an an auto-generated mail. kindly do not reply to this mail. Thank You. ****" . $newline . $newline;
$body_admin = $body_admin . $newline . $newline . $newline . $body_footer;
$to_admin1 = 'mymail#gmail.com';
mail ( $to_admin1, $subject_admin, $body_admin, $headers );
//error_mail(format_error( $errno, $errstr, $errfile, $errline));
}
}
function foo() {
return "foo";
}
function foo() {
return "foo";
}
// error_reporting(0); // This is not working, still error is displayed
// error_reporting(E_NONE); // This is not working, still error is displayed
// ini_set ( 'display_errors', 0 ); // This is not working, still error is displayed
echo "hello";
?>
update 3
Still getting same error
<?php
register_shutdown_function ( "fatal_handler" );
function fatal_handler() {
echo 'YAY IT WORKED';
}
function foo() {
return "foo";
}
function foo() {
return "foo";
}
// error_reporting(0); // This is not working, still error is displayed
// error_reporting(E_NONE); // This is not working, still error is displayed
// ini_set ( 'display_errors', 0 ); // This is not working, still error is displayed
echo "hello";
?>
Update4
<?php
//error_reporting(0);
function fatalErrorHandler() {
echo 'YAY IT WORKED';
}
# Registering shutdown function
register_shutdown_function('fatalErrorHandler');
// let force a Fatal error -- function does not exist
functiontest();
echo "hello";
?>
<!--
output:
Fatal error: Call to undefined function functiontest() in ...test2.php on line 12
YAY IT WORKED -->
<?php
error_reporting(0);
function fatalErrorHandler() {
echo 'YAY IT WORKED';
}
# Registering shutdown function
register_shutdown_function('fatalErrorHandler');
// let force a Fatal error -- function does not exist
functiontest();
echo "hello";
?>
<!-- output:
YAY IT WORKED -->
Final update:
This resolved my intermediate question
register_shutdown_function is not getting called
If I were you I would call my host and ask them to make the changes to my phpini. They may have special things setup.
Now you should never just hide errors. You send yourself an email and fix right away. The error you are trying to surpress is fatal and the script will no longer run, so hiding it only results in a blank page, the user stkill cannot continue.
It is a fatal error and you cannot recover from it. The way to hide fatal error properly in my opinion is to create your own error handler function.
And you would use something like this to catch the fatal errors.
http://php.net/manual/en/function.register-shutdown-function.php
The function needs to be on every page in order to catth the error. I have a error.php that I require in my db class, which is on every page.
//This function gets called every time your script shutsdown
register_shutdown_function( "fatal_handler" );
function fatal_handler() {
$errfile = "unknown file";
$errstr = "shutdown";
$errno = E_CORE_ERROR;
$errline = 0;
$error = error_get_last();
if( $error !== NULL) {
$errno = $error["type"];
$errfile = $error["file"];
$errline = $error["line"];
$errstr = $error["message"];
//send error email
error_mail(format_error( $errno, $errstr, $errfile, $errline));
}
}
UPDATE
**OP said the function is not being called. **
The above should work.
Here is basically what I use in production, it should tottally work.
ON_SCREEN_ERRORS and SEND_ERROR_EMAIL are my own config constants for development.
//Set error handler function (See function below)
set_error_handler("StandardErrorHandler");
/**
* Will take an error string and if ON_SCREEN_SQL_ERRORS is set to on, it will display the error on the screen with the SQL in a readable format and
* if SEND_SQL_ERROR_EMAILS is set to on, it will dendthe error email with the SQL in a readable format.
*
* PHP will pass these parameters automatically on error.
*
* #param string $errno The error type code.
* #param string $errstr The error string.
* #param string $errfile The file that the error occured in.
* #param string $errline The line number that the error occured.
*/
function StandardErrorHandler($errno, $errstr, $errfile, $errline) {
$Err = $errstr.'<br />'.GetErrorType($errno).'on line '.$errline.' in '.$errfile.'<br />';
if (ON_SCREEN_ERRORS===TRUE)
{
err($Err);
}
if ($errno =='256' and SEND_ERROR_EMAILS === TRUE)
{
$Path = "http://". $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// Custom error function
gfErrEmail($Err, $Path, 'SQL Error');
}
}
//Set the Fatal Error Handler function (See function below)
register_shutdown_function("FatalErrorHandler");
/**
* This function gets called on script shutdown, it will check if the last error is a fatal error. You cannot catch fatal errors,
* but using this function we will be notified about it and be able to fix it.
* If error is fatal, and if ON_SCREEN_FATAL_ERRORS is set to ON, this function will display the fatal error on the screen.
* If error is fatal, and if SEND_FATAL_ERROR_EMAILS is set to ON, this function will send error email.
*
*/
function FatalErrorHandler() {
$error = error_get_last();
if($error !== NULL) {
//check if error is of fatal, compliler or other non recoverable error types
if ($error["type"] =='1' || $error["type"] =='4' || $error["type"] =='16' || $error["type"] =='64' || $error["type"] =='4096')
{
$errno = GetErrorType($error["type"]);
$errfile = $error["file"];
$errline = $error["line"];
$errstr = $error["message"];
$Err = '<strong>'.$errno.'<br/></strong>'.$errstr.'<br />'.$errno.' on line '.$errline.' in '.$errfile.'<br />';
if (ON_SCREEN_ERRORS===TRUE)
{
err($Err);
}
if (SEND_ERROR_EMAILS === TRUE)
{
$Path = 'http://'. $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
//Custom function
gfErrEmail($Err, $Path, $errno);
}
}
}
}
/**
* This function receives the error code and returns the specified string.
* The return strings are what the error message will display.
*
* #return string The error title
*/
function GetErrorType($Type)
{
switch($Type)
{
case 1:
// 'E_ERROR';
return 'Fatal Error ';
case 2:
// 'E_WARNING';
return 'Warning ';
case 4:
// 'E_PARSE';
return 'Compile Time Parse Error ';
case 8:
// 'E_NOTICE';
return 'Notice ';
case 16:
// 'E_CORE_ERROR';
return 'Fatal Start up Error ';
case 32:
// 'E_CORE_WARNING';
return 'Start Up Warning ';
case 64:
//'E_COMPILE_ERROR';
return 'Fatal Compile Time Error ';
case 128:
// 'E_COMPILE_WARNING';
return 'Compile Time Warning ';
case 256 :
// 'E_USER_ERROR' - USED FOR SQL ERRORS - DO NOT USE THIS ERROR CODE to TRIGGER_ERROR()
return 'SQL Error ';
case 512:
// 'E_USER_WARNING';
return 'Warning - Thrown using trigger_error() ';
case 1024:
// 'E_USER_NOTICE';
return 'Notice - Thrown using trigger_error() ';
case 2048:
// 'E_STRICT';
return 'Strict Error (PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.) ';
case 4096:
// 'E_RECOVERABLE_ERROR';
return 'Catchable Fatal Error (This error can be caught, use a Try Catch) ';
case 8192:
// 'E_DEPRECATED';
return 'Warns you of depreciated code that will not work in future versions of PHP. ';
case 16384:
// 'E_USER_DEPRECATED';
return 'Programmer Triggered Error - Thrown using trigger_error() ';
}
return "Error Type Undefined ";
}

PHP custom error handler log to output

I have a script that will run on server daily to download data from a resource with no HTML output. By default PHP will output my script errors to php_error.log and to the output window in NetBeans.
I have created a user error handler:
// user defined error handling function
function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars)
{
error_log($errmsg, 3, "logs/aem.log");
switch ($errno) {
case E_ERROR:
exit("Error grave $errmsg at $filename:$linenum");
break;
case E_USER_ERROR:
exit("Error grave $errmsg at $filename:$linenum");
break;
}
}
error_reporting(0);
set_error_handler('userErrorHandler');
I include this file in my main script and everything goes fine.
While I develop the app I would like to continue seeing the error messages on Output screen in Netbeans as well as keeping the error log files (as the default handler does). I have tried changing the value of error_reporting or adding additional error_log functions trying the following values:
error_reporting(E_ALL | E_STRICT);
error_reporting(-1);
error_log($errmsg, 0);`
But I never get the error on the output unless I remove include('mycustomhandler'); from the file.
How can I emulate the behavior of the standard error handler?
You should try to use output to stderr (I guess netbeans parses it). For example:
fprintf( STDERR, "Normal error message %s\n", "With nested info");
For logging errors you may use error_log() (maybe will handle output to netbeans too) or try to parse error_log from php.ini (ini_get()).
However I guess php uses internaly syslog(). So your error handler should look like:
// Logging
function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars){
$logLevel = 0;
$label = '';
$exit = false;
switch( $errno){
case E_ERROR:
case E_USER_ERROR:
$label = 'Critical error';
$exit = true;
$logLevel = LOG_ERR;
break;
// ...
}
$message = "$label: on line ... file, error string...";
if( $logLevel){
syslog( $logLevel, $message);
}
if( !ini_get( 'display_error') && $exit){
die( 'Fatal error occured.');
}
if( $label){
echo $message; // You're responsible for how error is displayed
}
if( $exit){
die();
}
}
error_reporting( E_ALL);
Ask questions in comments if I didn't hit what you were asking

Can I call die after echo with PHP?

I'm trying to add some error checking inside my PHP script. Is it valid to do this:
if (!mkdir($dir, 0)) {
$res->success = false;
$res->error = 'Failed to create directory';
echo json_encode($res);
die;
}
Is there a better way to exit the script after encountering an error like this?
That looks fine to me.
You can even echo data in the die like so:
if (!mkdir($dir, 0)) {
$res->success = false;
$res->error = 'Failed to create directory';
die(json_encode($res));
}
Throwing a exception. Put code into a try catch block, and throw exception when you need.
PHP has functions for error triggering and handling.
if (!mkdir($dir, 0)) {
trigger_error('Failed to create directory', E_USER_ERROR)
}
When you do this the script will end. The message will be written to the configured error log and it will also be displayed when error_reporting is enabled.

Categories