PHP Error Logs + Add a Session Value to the log entry - php

This is most likely a silly question so I have no issues with it being closed etc.
I'm debugging PHP error logs and it would be of great advantage if I could see the user that created the specific error.
The userid is keep in the session.
Is it possible to customize PHP error logs to include a session value for debugging?
thx

Of course it is possible, I don't see why not:
try {
//some code
} catch (Exception $e) {
session_start();
$log = 'Caught exception: '. $e->getMessage(). "\n";
$log .= 'By user = '.$_SESSION['user_id']. "\n";
error_log($log);
}
To change error messages into Exception use this code:
<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
/* Trigger exception */
strpos();
?>
ErrorException

Related

How to catch "No error: PDO constructor was not called"

how can I catch the following error: No error: PDO constructor was not called?
My question is not how to solve the error, but how to catch it!
I need that for a PHPUnit Testing Environment.
I was trying to catch it like that, but it simply doesn't work that way.
$pdo = (new \ReflectionClass(\PDO::class))->newInstanceWithoutConstructor();
try
{
$pdo->query("SELECT * FROM table");
}
catch (ErrorException $exc)
{
echo $exc->getTraceAsString();
}
the exact (error) message is as follows: PDO::query(): SQLSTATE[00000]: No error: PDO constructor was not called, but I am not sure, if that is even any type of PHP catchable.
I've already checked the method pdo_raise_impl_error()[PHP 7.3.3] that is called with the mentioned error message, but I am not wise enough to anticipate what actual type of error it produces...
Can please someone give advise?
Not sure if it's a solution you are looking for, but you can always convert all errors to exceptions with as simple code as
set_error_handler(function ($level, $message, $file = '', $line = 0)
{
throw new ErrorException($message, 0, $level, $file, $line);
});
Of course it will make a global error handler, but honestly, I believe every PHP project should have a code like this.
Or at least you can call this handler only temporarily
I now use the following code fore my test.
please check the first and the last line of code especially.
thanks to #YourCommonSense!
set_error_handler(function(int $errno, string $errstr, string $errfile, int $errline) {
throw new ErrorException($errstr, $errno, E_ERROR, $errfile, $errline);
});
$this->expectException(ErrorException::class);
$this->expectExceptionMessage("SQLSTATE[00000]: No error: PDO constructor was not called");
/* #var $pdo PDO */
$pdo = (new ReflectionClass(PDO::class))->newInstanceWithoutConstructor();
$pdo->query("SELECT * FROM table"); // triggers the error.
restore_error_handler();

Customizing PHP error messages

I want to change the following PHP error message so that user does not see this error and I would like to display an error which is more understandable by the user.
For example consider this error which I want to edit,
Notice: Undefined index: user_input on line 33
I want to display the following error message instead of the above default error message,
Process failed
How can I implement this on my website?
This is not an error it is a notice, so you will need to do few things:
First look into ErrorException you need to convert the notice to an exception.
Catch the exception
Print your custom error message
Example:
<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
try {
//Trigger exception:
$my_array = array();
echo $my_array['undefined'];//Notice will throw exception
} catch (Exception $e) {
echo 'Process failed';
}
?>
You should check to see if the variable is set and display the error message you want if it's not

PHP: can anyone explain this Exception Handler error?

hi can anyone here can help how to determine whats the error on here? please i really need to know. thank you in advance guys! help me to figure out what is wrong with the codes below.
function exception_error_handler($errno, $errstir, $errfile, $errline ) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);;
}
set_error_handler("exception_error_handler");
/* Trigger exception */
strpos();
i don't know whats the error on this but it stills keeping an error output. pls help me guys
In PHP notices and warnings don't throw exceptions. Calling strpos() without parameters is a warning. That function registers your custom function as the error_handler, which basically converts all notices and warnings to an exception. It' useful for development and debugging, and a lot of frameworks use something like that to show error pages in development mode.
Could you try the following code which catches the custom ErrorException which you throw?:
function exception_error_handler($errno, $errstir, $errfile, $errline ) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);;
}
set_error_handler("exception_error_handler");
try {
/* Trigger exception */
strpos();
echo 'No exception was thrown';
}
//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}

How to get file_get_contents() warning instead of the PHP error?

file_get_contents('https://invalid-certificate.com');
Yields the following PHP warning and error:
PHP warning: Peer certificate CN='*.invalid-certificate.net' did not match expected CN='invalid-certificate.com'
PHP error: file_get_contents(https://invalid-certificate.com): failed to open stream: operation failed
I want to use exceptions instead of the PHP warning, so:
$response = #file_get_contents('https://invalid-certificate.com');
if ($response === false) {
$error = error_get_last();
throw new \Exception($error['message']);
}
But now the exception message is:
file_get_contents(https://invalid-certificate.com): failed to open stream: operation failed
That's normal, error_get_last() returns the last error…
How can I get the warning, which contains much valuable information regarding the failure?
You can make good use of set_error_handler and convert those errors into exceptions and use exceptions properly
<?php
set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
try {
$response = file_get_contents('https://invalid-certificate.com');
} catch (ErrorException $e) {
var_dump($e); // ofcourse you can just grab the desired info here
}
?>
A much simpler version would be
<?php
set_error_handler(function($errno, $errstr) {
var_dump($errstr);
});
$response = file_get_contents('https://invalid-certificate.com');
?>
Fiddle

Debugging PRG in php - how to get errors to show?

How does one get php to stop on a non-fatal error inside a PRG (POST-Redirect-GET) segment, so you can see the error message, without the subsequent header() used for the redirect wiping out the error message?
Example Caller.htm
<form method="post" action="Callee.php">
<input type="text" name="PostData" />
<input type="submit" value="Go" />
</form>
Example Callee.php:
<?php
// POST section:
if($_POST) {
$var = $x; // non-fatal error: $x is missing.
header("Location: ". $_SERVER['REQUEST_URI']. 'Query'); die; // Redirect & GET
}
// GET section
// ...
What happens is that when testing, php reports the error for the missing $x, but then keeps moving, hits the header() and discards the error output, so you never see the error message on your screen.
You can temporarily put a die; (or exit;) just before the header, or comment out the header to test the code. Then when the code is working take out the die; or put the header back in. But this doesn't work very well in development as I've found a number of times an error crept in that I didn't even know was there.
Sometimes you can move the header up above where the errors are likely to occur. However, in the more general case one needs to be able to pass a query string to the GET section, so the header must be at the bottom of the POST section.
I think this might be what php calls an E_WARNING, "Run-time warnings (non-fatal errors). Execution of the script is not halted.", but I'm not sure.
I'm running 5.4.23:
error_reporting = E_ALL | E_STRICT
display_errors = "On"
log_errors = "On"
ignore_repeated_errors = "Off"
[All that I tried deleted. Jack has the answer below.]
First of all, you should assume things go right, so the redirect should take place inside the try scope:
if($_POST) {
try{
$var = $x; //BAD CODE, $x is missing.
header("Location: ". $_SERVER['REQUEST_URI']); // Redirect & GET
} catch (Exception $e) {
echo $e->getMessage();
}
exit;
}
Now, if you want your code to throw exceptions on warnings and notices, have a look at ErrorException and define a custom error handler that turns them into exceptions:
function exception_error_handler($errno, $errstr, $errfile, $errline )
{
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
Above code is taken from the documentation.
Preferably, you will want to use an error logger (related question):
// ...
} catch (Exception $e) {
$logger->fatal($e); // or $this->fatal($e);
}
Putting it together
function exception_error_handler($errno, $errstr, $errfile, $errline )
{
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
if($_POST) {
try{
$var = $x; //BAD CODE, $x is missing.
header("Location: ". $_SERVER['REQUEST_URI']); // Redirect & GET
} catch (Exception $e) {
echo $e->getMessage(); // or log the exception
}
exit;
}
Try echo your input;
echo $_SERVER['REQUEST_URI'];
You can see if your input is empty: before being redirected by header();

Categories