How to prevent ob_start() output when an error occur? - php

Please, consider the following example:
template.php:
<?php
echo $vars['arr'];
echo " -------- ";
echo $vars['obj'];
?>
test.php:
<?php
$file = "template.php";
$vars = array( 'arr' => array(), 'obj' => new StdClass() );
var_dump( json_encode($vars) );
function loadFile($file, $vars)
{
try
{
if (is_array($vars) && !empty($vars)) {
extract($vars);
}
ob_start();
include $file;
return ob_get_clean();
}
catch (Exception $e)
{
return false;
}
}
loadFile($file, $vars);
?>
This code will output:
string(19) "{"arr":[],"obj":{}}"
PHP Catchable fatal error: Object of class stdClass could not be converted to string in template.php
The problem here is, in the template.php I am considering $vars to be an array() however 1 of the elements is an Object as you can see from the json output.
Adding a simple checking in the template to verify if the ekement is an array or not would solve the problem, however I would need to this to multiple elements, elements, so, not very good =) so, I trying to find a way to prevent the error in the moment of binding the template and $vars.
Thank you

simply turn error_reporting off while parsing:
$old_level = error_reporting(0); // no errors, preserve old error reporting level
ob_start();
include $file;
$content = ob_get_clean();
error_reporting($old_level); // reset error reporting level
return $content;
Note: This will only hide errors that aren't very critical.
In order to catch a Catchable Fatal Error, see this question: How can I catch a "catchable fatal error" on PHP type hinting?
You need to register an error handler using set_error_handler:
function handleError($errno, $errstr, $errfile, $errline) {
// handle error
// return true, so the normal php handler doesn't get called
return true;
}
set_error_handler('handleError');
If you want to integrate you handler cleanly into other code which also sets error_handlers, you might consider restoring the error handler afterwards using restore_error_handler

You might try checking to see if the values are an object first, and then using the PHP function to convert to an array.
Note, this section of your code:
if (is_array($vars) && !empty($vars)) {
extract($vars);
}
After that, if I'm reading your code correctly, you have a variable possibly called $vars that could be an object. So, you could do this:
if (is_object($vars)) {
$vars = get_object_vars($vars);
}
That should convert it to what you need. Of course, you may need to experiment a bit to make sure it fits your scenario. Thanks!

You can use __toString() method in your class to avoid the error. You can set the __toString() method with any value you need, maybe return an array.
http://www.php.net/manual/en/language.oop5.magic.php#object.tostring
Another option, is use array_walk :
function checkObj(&$vars){
if (is_object($vars)) {
$vars = get_object_vars($vars);
}
}
array_walk($vars, "checkObj");

Since you are using ob_start(), you can pass it a call-back that will check for any errors. It should even work with fatal errors. Inside your call-back use something like "error_get_last" to check for any error and just return false if it's not null, like so:
WARNING: I've not tested this code, but I use something similar myself.
<?php
$file = "template.php";
$vars = array( 'arr' => array(), 'obj' => new StdClass() );
var_dump( json_encode($vars) );
function loadFile($file, $vars)
{
try
{
if (is_array($vars) && !empty($vars)) {
extract($vars);
}
ob_start('errorHandler');
include $file;
return ob_get_clean();
}
catch (Exception $e)
{
return false;
}
}
function errorHandler($pBuffer)
{
$lastError = error_get_last();
// Uh-oh, an error has occurred.
if ($lastError !== NULL)
{
return FALSE;
}
// No problems.
return $pBuffer;
}
loadFile($file, $vars);
?>

Related

php make set_error_handler return an error string

I need to put a contents of 'PHP Warning' into a variable. For these purposes I got the following code (set_error_handler() in a php class):
$data = '';
set_error_handler( function() use ($this, &$data) { $data = $this->my_error_handler(); return $data; } );
//some code that throws Warning
restore_error_handler();
function my_error_handler($errno, $errstr) {
return $errstr;
}
But I get the following 500 error: Type error: Too few arguments to function my_error_handler(), 0 passed.
If I replace a callable above with a string, code works without a 500 error, but I cannot pass a variable in it and return it with a contents of warning thrown. Any ideas how to fix it? Thank you.

PHPUnit expect exception failing due to foreach warning

I want to test that a method called foo() throws an exception. The problem is that I can't get PHPUnit expectException() to catch the exception.
foo() looks something like this:
public function foo()
{
$params = $this->readAndFormatConfig();
// exception actually gets thrown in this method
$this->method->throws->exception($params);
}
If I catch the exception manually it works fine, like this:
public function testFoo()
{
$badConfig = new Config([]);
$driver = new bar($badConfig);
$exceptionThrown = false;
try {
$driver->foo();
} catch (Exception $e) {
$exceptionThrown = true;
}
$this->assertTrue($exceptionThrown);
}
If I catch it using expectException, like this:
public function testFoo()
{
$badConfig = new Config([]);
$driver = new bar($badConfig);
$this->expectException(Exception::class);
$driver->foo();
}
the test fails and I get this exception:
MyTestClass::testFoo Invalid argument supplied for foreach()
The output of get_class($e) is PHPUnit_Framework_Error_Warning which surprised me, but explains why the first test works but the second doesn't.
I'd like to either ignore the warning and wait until a real exception is thrown, or get the original warning, not PHPUnit_Framework_Error_Warning.
I'm using php 5.6.32 and PHPUnit 5.7.15
Adding the following to boostrap.php converts warnings to exceptions.
function warningToException($errno, $errstr, $errfile, $errline)
{
throw new Exception($errstr . " on line " . $errline . " in file " . $errfile);
}
set_error_handler("warningToException", E_WARNING);
This allowed the following test pass.
public function testFoo()
{
$badConfig = new Config([]);
$driver = new bar($badConfig);
$this->expectException(Exception::class);
$driver->foo();
}
I think a better method would be to expect PHPUnit_Framework_Error_Warning in the test as ishegg suggested.
What I ended up actually doing was making sure the object I was passing to foreach was traversable before entering the loop.
public function foo()
{
if (is_array($x) || $x instanceof \Traversable) {
// do stuff
} else {
// return false;
}
}
I think it makes more sense to refactor the application code in this case. What I'm really trying to test is that the function foo returns false if the application is misconfigured, so handling the misconfiguration properly seems like the right path in my opinion.
If you stumble upon this question for some reason and really need to convert warnings to an exception class other than PHPUnit_Framework_Error_Warning this is how I did it.
Thanks to ishegg for pointing me in the right direction.

Why not output I hope result in PHP7 using try and catch? [duplicate]

I need to catch some warnings being thrown from some php native functions and then handle them.
Specifically:
array dns_get_record ( string $hostname [, int $type= DNS_ANY [, array &$authns [, array &$addtl ]]] )
It throws a warning when the DNS query fails.
try/catch doesn't work because a warning is not an exception.
I now have 2 options:
set_error_handler seems like overkill because I have to use it to filter every warning in the page (is this true?);
Adjust error reporting/display so these warnings don't get echoed to screen, then check the return value; if it's false, no records is found for hostname.
What's the best practice here?
Set and restore error handler
One possibility is to set your own error handler before the call and restore the previous error handler later with restore_error_handler().
set_error_handler(function() { /* ignore errors */ });
dns_get_record();
restore_error_handler();
You could build on this idea and write a re-usable error handler that logs the errors for you.
set_error_handler([$logger, 'onSilencedError']);
dns_get_record();
restore_error_handler();
Turning errors into exceptions
You can use set_error_handler() and the ErrorException class to turn all php errors into exceptions.
set_error_handler(function($errno, $errstr, $errfile, $errline) {
// error was suppressed with the #-operator
if (0 === error_reporting()) {
return false;
}
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
try {
dns_get_record();
} catch (ErrorException $e) {
// ...
}
The important thing to note when using your own error handler is that it will bypass the error_reporting setting and pass all errors (notices, warnings, etc.) to your error handler. You can set a second argument on set_error_handler() to define which error types you want to receive, or access the current setting using ... = error_reporting() inside the error handler.
Suppressing the warning
Another possibility is to suppress the call with the # operator and check the return value of dns_get_record() afterwards. But I'd advise against this as errors/warnings are triggered to be handled, not to be suppressed.
The solution that really works turned out to be setting simple error handler with E_WARNING parameter, like so:
set_error_handler("warning_handler", E_WARNING);
dns_get_record(...)
restore_error_handler();
function warning_handler($errno, $errstr) {
// do something
}
Be careful with the # operator - while it suppresses warnings it also suppresses fatal errors. I spent a lot of time debugging a problem in a system where someone had written #mysql_query( '...' ) and the problem was that mysql support was not loaded into PHP and it threw a silent fatal error. It will be safe for those things that are part of the PHP core but please use it with care.
bob#mypc:~$ php -a
Interactive shell
php > echo #something(); // this will just silently die...
No further output - good luck debugging this!
bob#mypc:~$ php -a
Interactive shell
php > echo something(); // lets try it again but don't suppress the error
PHP Fatal error: Call to undefined function something() in php shell code on line 1
PHP Stack trace:
PHP 1. {main}() php shell code:0
bob#mypc:~$
This time we can see why it failed.
I wanted to try/catch a warning, but at the same time keep the usual warning/error logging (e.g. in /var/log/apache2/error.log); for which the handler has to return false. However, since the "throw new..." statement basically interrupts the execution, one then has to do the "wrap in function" trick, also discussed in:
Is there a static way to throw exception in php
Or, in brief:
function throwErrorException($errstr = null,$code = null, $errno = null, $errfile = null, $errline = null) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
function warning_handler($errno, $errstr, $errfile, $errline, array $errcontext) {
return false && throwErrorException($errstr, 0, $errno, $errfile, $errline);
# error_log("AAA"); # will never run after throw
/* Do execute PHP internal error handler */
# return false; # will never run after throw
}
...
set_error_handler('warning_handler', E_WARNING);
...
try {
mkdir($path, 0777, true);
} catch (Exception $e) {
echo $e->getMessage();
// ...
}
EDIT: after closer inspection, it turns out it doesn't work: the "return false && throwErrorException ..." will, basically, not throw the exception, and just log in the error log; removing the "false &&" part, as in "return throwErrorException ...", will make the exception throwing work, but will then not log in the error_log... I'd still keep this posted, though, as I haven't seen this behavior documented elsewhere.
Combining these lines of code around a file_get_contents() call to an external url helped me handle warnings like "failed to open stream: Connection timed out" much better:
set_error_handler(function ($err_severity, $err_msg, $err_file, $err_line, array $err_context)
{
throw new ErrorException( $err_msg, 0, $err_severity, $err_file, $err_line );
}, E_WARNING);
try {
$iResult = file_get_contents($sUrl);
} catch (Exception $e) {
$this->sErrorMsg = $e->getMessage();
}
restore_error_handler();
This solution works within object context, too. You could use it in a function:
public function myContentGetter($sUrl)
{
... code above ...
return $iResult;
}
Normaly you should never use # unless this is the only solution. In that specific case the function dns_check_record should be use first to know if the record exists.
If dns_get_record() fails, it should return FALSE, so you can suppress the warning with # and then check the return value.
You should probably try to get rid of the warning completely, but if that's not possible, you can prepend the call with # (i.e. #dns_get_record(...)) and then use any information you can get to figure out if the warning happened or not.
try checking whether it returns some boolean value then you can simply put it as a condition. I encountered this with the oci_execute(...) which was returning some violation with my unique keys.
ex.
oci_parse($res, "[oracle pl/sql]");
if(oci_execute){
...do something
}
As of PHP8, you can do the following instead of setting error handlers to catch Errors and Warnings. I Believe in PHP 7.something you could catch some Errors.
try {
call_user_func('sprintf', array_merge([$string], $args));
} catch (Throwable $e) {
$logger->info('mesage...');
}
You should generally be somewhere that you can pass or access a logger if you bulkhead in this way, as it can obfuscate coder errors, such as passing incorrectly typed parameters to a method, and mask a variety of other problems.
https://php.watch/versions/8.0/internal-function-exceptions
Not sure if notices are caught (likely not), but you can likely solve around examples like this one, by thinking a little more about what you are looking to do.
Both builder pattern, and options patterns provide solutions for this where prior to the site of call, which can be a private function or just after validity checks, you can throw a real custom exception that is attributable only to your code. That will make even built-in functions very safe to use.
One other nice practice is to use either debug_backtrace, with DEBUG_BACKTRACE_IGNORE_ARGS or use the getTrace or getTraceAsString methods on the Throwable so that some of the context is preseved.
FolderStructure
index.php //Script File
logs //Folder for log Every warning and Errors
CustomException.php //Custom exception File
CustomException.php
/**
* Custom error handler
*/
function handleError($code, $description, $file = null, $line = null, $context = null) {
$displayErrors = ini_get("display_errors");;
$displayErrors = strtolower($displayErrors);
if (error_reporting() === 0 || $displayErrors === "on") {
return false;
}
list($error, $log) = mapErrorCode($code);
$data = array(
'timestamp' => date("Y-m-d H:i:s:u", time()),
'level' => $log,
'code' => $code,
'type' => $error,
'description' => $description,
'file' => $file,
'line' => $line,
'context' => $context,
'path' => $file,
'message' => $error . ' (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']'
);
$data = array_map('htmlentities',$data);
return fileLog(json_encode($data));
}
/**
* This method is used to write data in file
* #param mixed $logData
* #param string $fileName
* #return boolean
*/
function fileLog($logData, $fileName = ERROR_LOG_FILE) {
$fh = fopen($fileName, 'a+');
if (is_array($logData)) {
$logData = print_r($logData, 1);
}
$status = fwrite($fh, $logData . "\n");
fclose($fh);
// $file = file_get_contents($filename);
// $content = '[' . $file .']';
// file_put_contents($content);
return ($status) ? true : false;
}
/**
* Map an error code into an Error word, and log location.
*
* #param int $code Error code to map
* #return array Array of error word, and log location.
*/
function mapErrorCode($code) {
$error = $log = null;
switch ($code) {
case E_PARSE:
case E_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
$error = 'Fatal Error';
$log = LOG_ERR;
break;
case E_WARNING:
case E_USER_WARNING:
case E_COMPILE_WARNING:
case E_RECOVERABLE_ERROR:
$error = 'Warning';
$log = LOG_WARNING;
break;
case E_NOTICE:
case E_USER_NOTICE:
$error = 'Notice';
$log = LOG_NOTICE;
break;
case E_STRICT:
$error = 'Strict';
$log = LOG_NOTICE;
break;
case E_DEPRECATED:
case E_USER_DEPRECATED:
$error = 'Deprecated';
$log = LOG_NOTICE;
break;
default :
break;
}
return array($error, $log);
}
//calling custom error handler
set_error_handler("handleError");
just include above file into your script file like this
index.php
error_reporting(E_ALL);
ini_set('display_errors', 'off');
define('ERROR_LOG_FILE', 'logs/app_errors.log');
include_once 'CustomException.php';
echo $a; // here undefined variable warning will be logged into logs/app_errors.log
Since PHP7 you can catch most errors and warnings like so:
try {
whatever();
} catch (Throwable $e) {
}
More: https://www.php.net/manual/en/language.errors.php7.php
I would only recommend using # to suppress warnings when it's a straight forward operation (e.g. $prop = #($high/($width - $depth)); to skip division by zero warnings). However in most cases it's better to handle.

php Exception By getting a class that might exists

i try to make a function that load classes that are in the array. but it can be the case that the class don't exists, in that case i want to get an error string that an be places on that place and if it exists than the class has to be on that place.
so i thought i going to use try,catch to catch the error, but i stell get tge error.
try {
$content = $extension::content();
} catch (Exception $e) {
$content = '[undefined extension:'.$extension.']';
}
who can help me out
thanks
try using class_exists() documentation here
e.g
<?php
if( class_exists( $extension ) )
{
$content = $extension::content();
}else{
$content = '[undefined extension:'.$extension.']';
}
if ( class_exists($extension) && property_exists($extension, 'content') ) {
$content = $extension::content();
}else{
$content = '[undefined extension:'.$extension.']';
}
Since PHP5 you can autoload classes. As soon as you try to load a class that PHP does not know about it will run your custom function which will then be able to locate the class or throw an Exception of its non-existence.
Read about it here:
http://php.net/manual/en/language.oop5.autoload.php
In PHP, by default errors aren't exception and can't be catched. However, you can use set_exception_handler to throw an exception when a error occurs. Sadly, fatal error cannot be handled with this method.
To check if a class exists, you can call class_exists.

Standard PHP error function with __LINE__ __FILE__etc?

so, instead of lots of instances of
if (odbc_exec($sql))
{
}
else
{
myErrorHandlingFunction();
}
I wrap that in a function
function myOdbxExec($sql)
{
if (odbc_exec($sql))
{
}
else
{
myErrorHandlingFunction();
}
}
BUT I would like myErrorHandlingFunction() to report things like __LINE__ __FILE__ etc
Which looks like I have to pass thoses infos to every call of helper functions, e.g. myOdbxExec($sql, __FILE__, __LINE__) which makes my code look messy.
function myErrorHandlingFunction($errorTExt, $fiel, $line)
{
// error reporting code goes here
}
function myOdbxExec($sql, $file, $line)
{
if (odbc_exec($sql))
{
}
else
{
myErrorHandlingFunction();
}
}
$sql = 'select * from ... blah, blah, blah...';
myOdbxExec($sql, __FILE__, __LINE__); // <==== this is *ugly*
In C I would hide it all behind a #define, e.g. #define MY_OFBC_EXEC(sql) myOdbxExec(sql, __FILE__, __LINE__)
1) (how) can I do that in PHP
2) what else is worth outoputting? e.g. error_get_last()? but that has no meaning if odbc_exec() fails ...
To rephrase the question - what's the generic approach to PHP error handling? (especially when set_error_handler() doesn't really apply?
Edit: just to be clear - I do want to handle exceptions, programming errors, etc, but, as my example shows, I also want to handle soemthings the teh PHP interpreter might noit consider to be an error, like odbc_exec() returning false().
Both the above answers mentioning debug_backtrace are answering your _______LINE_____ / _______FILE___ question with the debug_backtrace() function. I've wanted this answer too in the past, so have put together a quick function to handle it.
function myErrorHandlingFunction($message, $type=E_USER_NOTICE) {
$backtrace = debug_backtrace();
foreach($backtrace as $entry) {
if ($entry['function'] == __FUNCTION__) {
trigger_error($entry['file'] . '#' . $entry['line'] . ' ' . $message, $type);
return true;
}
}
return false;
}
You can then call, for instance, myErrorHandlingFunction('my error message');
or myErrorHandlingFunction('my fatal error message', E_USER_ERROR);
or try { ... } catch (Exception $e) { myErrorHandlingFunction($e->getMessage()); }
First off, you might want to consider using exception handling.
If for some reason, that doesn't appeal to you, you can use debug_backtrace inside your generic error handler to figure out where the handler was called from.
EDIT In response to OP's comment:
Exceptions don't have to come from PHP built-ins. You can throw your own. Since an ODBC error generally is an exceptional condition, just throw an exception when you detect one. (And catch it at some higher level).
<?PHP
if (! odbc_exec($sql) )
throw new DatabaseException('odbc_exec returned false, that bastard!');
Use debug_backtrace to figure out where a function was called from in your error handler. Whether you invoke this error handler by manually calling it, by throwing and catching exceptions, PHPs error_handler or any other method is up to the application design and doesn't really differ that much from other languages.

Categories