CodeIgniter Helper function ignores all errors, output and even die() - php

I am new to CodeIgniter, but am very familiar with MVC frameworks such as Symfony.
I am making a change to a custom helper function, where I am retrieving data from the db. I do not think the DB retrieval is working, but I am not getting any errors. The helper function is simply ignoring errors. There are no errors in the log file (log_threshold = 4) and die() is also being ignored.
I am going to post the helper function below, but my question is not what is wrong with my code (if anything), the question is why are the errors and die() being ignored and what can I do to fix this?
function getRates() {
$ci=& get_instance();
$ci->load->database();
$ci->db->select('currency_values.*');
$ci->db->from('version1.currency_values');
$currencyValues = $ci->db->get();
$lastUpdated = strtotime($currencyValues->result()[0]->last_updated);
die(">>> $lastUpdated <<<"); //This gets ignored
if ($lastUpdated > time() - 600)
{
//Code here that SHOULD be running
}
else
{
//Code here that ALWAYS runs, most likely because db retrieval is not working
}

try to use try and catch and print the exception error
try
{
}
catch(Exception $e){
echo $e;
}

There is no way PHP is ignoring die() call. Confirm it by putting few dummy :
echo "1\n"; at multiple places or by
using exit() instead of die(). Though a complete guess, probably the interpreter is reading code from somewhere else. Such case if not that rare.
For the concern of no error being reported and DB retrieval failing, you may use PHP exception handling or set error_reporting to E_ALL.
error_reporting(E_ALL);
ini_set('display_errors', 1);

Related

Code Igniter: how not to show incomplete pages in case of error

1) I have a view (a neseted one) that triggers a notice-level error
2) I have set up a custom error handler, which is called. Code goes below
3) I want visitor seeing only the "error happened" string in his browser, instead, he sees the half-baked page with this error message appended
4) messing with php's native ob_end_clean only made me clear the contents of the deepest view involved, yet the higher-level views are still half-shown
5) the contents of final_output var of CI_Ouput class is empty string at the moment of error. That's strange is CI is said to pre-buffer everything befoew outputting to the client.
essentially, what I need seems to be discarding any content having been collected so far and replacing it with error message only.
how can I do it?
the code of the handler:
function _error_handler($errno, $errstr) {
echo "error happened";
die();
}
Try to use a Try Catch system?
Try{
//Do something
} catch(Exception $e){
echo "Error has occured!";
}
as suggested in the discussion this had to be related to php's native output buffering wich we can control with ob_* family of functions. Buffering in php can be nested, and CI seems to use it, opening a buffer for each view being loaded.
If we load a view from inside a view, the nesting gets deeper, and generally, when an error occures in the view we don't know how deep we are.
So that's what seems to solve the problem (the code of error handler):
function _error_handler($errno, $errstr) {
$currentLevel=ob_get_level();
for($i=0; $i<$currentLevel-1; $i++) {
ob_end_clean();
}
print "errorrrr!";
die();
}
so it detects how deep it is and cleans as many buffers as needed. After all, we end up with "errorrrr" message being the only thing on the page.

php session_start general error handling

I'm looking for a general way to handle session_start errors, not a way to handle one specific error. There are numerous errors which can happen, such as the session directory being full, which cause a fatal error. I want a way to trap those errors and handle them cleanly, without having to write custom handlers for each possibility.
Something like this (but not this as it doesn't work):
try{
session_start();
}catch(Exception $e){
echo $e->getMessage();
}
All help appreciated, thanks in advance.
The regular PHP session functions don't throw exceptions but trigger errors. Try writing an error handler function and setting the error handler before calling session_start.
function session_error_handling_function($code, $msg, $file, $line) {
// your handling code here
}
set_error_handler('session_error_handling_function');
session_start();
restore_error_handler();
However, this is just for capturing the session errors. A better way would be to create a general error handler that creates exceptions from errors and surround code parts that may throw errors with try ... catch blocks.

PHP/MySQL: What should I use to manage errors?

I have a website built using PHP and Mysqli and I'm at the part where I should think about my error handling.
Even if I think that my code is perfect errors will appear when I release the website to the public. I found this answer that shows how I can hide the errors for the users but the developer can still see them. Though I don't know if this is really the best approach for my site. I don't want the user to see ugly error messages produced my PHP itself but that I could design my own error message depending on the error.
How should I manage these errors? Should I save them all in a database?
How do I know which errors could occurr?
PHP has in-built function to catch various types of errors:
set_error_handler
You should use this function to capture the errors across all your pages, you can write custom code whether to insert errors to database, or to write into separate error log file, or to notify immediately through email to developers, you can decide.
I would start by using
try
{
//your code here
}
catch(Exception $ex)
{
echo $ex->getMessage();
}
When doing database queries. The error handling can be loggin it to a file or something like that.
That way you catch what's happening and set yourself what needs to be done....
error_reporting(E_ALL);
ini_set('display_errors','On');
ini_set('error_log', 'error.log');
ini_set('log_errors', 'On');
These functions will show errors if any also it will list errors in error.log.
If you want to hide the errors from appearing on site then you can set value from "on" to "off".
If you want to hide it only from users and not for developers then you can set "ini_set('display_errors','off');" so these will not visible to users but developers can resolve it from error.log
How should I manage these errors?
You should record them and analyse the logs to resolve them (or at least ensure your site is secure).
Should I save them all in a database?
No - you're going to lose visibility of database connectivity issues. The right way is via the syslog functionality on the local machine.
How do I know which errors could occurr?
? All of them.
Handling errors is one of the most important aspects of an application. The users expects it to work, but when an error occurs their may loose confidence into your application, no matter who good it is. I learned it the hard way.
We use a class similar to the following:
class ErrorHandler
{
public static function registerHandlers()
{
$inst = new ErrorHandler;
set_error_handler(array(&$inst, 'errorHandler'), E_ALL);
set_exception_handler(array(&$inst, 'exceptionHandler'));
register_shutdown_function(array(&$inst, 'shutdownHandler'));
}
public function shutdownHandler()
{
if (($error = error_get_last()))
{
$this->_clearOutputBuffers();
// Handle error
}
}
public function errorHandler($errno, $errstr, $errfile, $errline, $errcontext)
{
$this->_clearOutputBuffers();
// Handle error
}
public function exceptionHandler(Exception $exception)
{
$this->_clearOutputBuffers();
// Handle error
}
private function _getErrorCode($sMessage, $sFile, $nLine, $nCode)
{
$errorCode = sprintf("%u", crc32($sMessage.$sFile.$nLine.$nCode));
}
private function _clearOutputBuffers()
{
if (count(ob_list_handlers()) > 0)
{
ob_clean();
}
}
}
This class is able to catch most errors and works surprisingly well for debugging purposes as well. When ever an error is caught we write all the information to a file that we can reference later. Further we separate our environments between development and production and have separate error screens for it.
For the development environment we use an error screen that displays the extract of the file a stack trace and variables.
For the production environment we display an error screen containing the error number returned from _getErrorCode. If a customer wants to contact us about the error, all he has to do is tell us the number and we can instantly look it up and have all the data in front of us.
I have attached a screenshot of our development error screen.

includes many php-files in one pgm and catch errors

i call an php pgm per cronjob at different times.
the pgm includes many php-files.
each file sends or gets data from partners.
How can i handle errors in one includes pgm.
at the time, one ftp-connection in an included pgm fails so the complete script crushes.
how can i handle this ?
You should wrap code, which is possible to crash, into try/catch construction. This will throw exeption, but the script will continue to work. More here.
Need to know more about you code inorder to give you definite answer.
In general php errors isn't catchable unless you define your own error handler from which you throw exceptions your self. Using the code below makes most runtime errors catchable (as long as they arent considered fatal)
error_reporing(E_ALL);
set_error_handler(function($errno, $errstr, $errfile, $errline) {
if($errno == E_STRICT || $errno == E_DEPRECATED) {
return true;
}
throw new RuntimeException('Triggered error (code '.$errno.') with message "'.$errstr.'"');
});
Btw, You could also define your own exception handler to display triggered errors with a full stack trace when an exception isn't catched.
Notice! I would not suggest that you add this code to a production website without rigorous testing first, making sure everything still works as expected.
Edit:
I have no idea what your code looks like, but I guess you can do something like:
require 'error-handler.php'; // where you have your error handler (the code seen above)
$files_to_include = array(
'some-file.php',
'some-other-file.php',
...
);
foreach($files_to_include as $file) {
try {
include $file;
}
catch(Exception $e) {
echo "$file failed\nMessage: ".$e->getMessage()."\nTrace:\n".$e->getTraceAsString();
}
}

PHP - Do something if no errors/warnings occur in set of expressions

I have a page that will basically be used to concatenate a bunch of xml files, it will act as glue that binds them together. There's a small chance the xml files that are being combined might not be well formed because the user will have access.
I'm trying to basically rewrite a live file if there are no warnings / errors thrown in a specific set of code.
So far I have:
try {
$first = simplexml_load_file( 'file.xml' );
} catch ( Exception $e ) {
$write = false;
}
if ( !$write ) {
// write to live file.
}
This obviously catches error exceptions, but sometimes function invocations can return warnings and not errors per se, what can I use to catch errors, basically only write if no warnings and errors have been thrown in the try block?
Example of a warning being thrown:
Warning: simplexml_load_file() parser error : Start tag expected, '<'
Just look for other "symptoms" of a failed read. From the simplexml_load_file manual entry:
Return Values
Returns an object of class SimpleXMLElement with properties containing the data held within the XML document. On errors, it will return FALSE.
So, use it like this:
$first = simplexml_load_file( 'file.xml' );
if ($first == false) {
echo "File couldn't be loaded";
exit(); // abort normal program execution, redirect or what have you
}
// continue as normal
Almost all functions return some sort of false in case of an error. You shouldn't use manual "error parsing" except for very special cases. This isn't one of them.
A few things come to mind for this situation. if you will always have warnings enabled (not a great idea for a production server) you can always use the output buffering functions to check if there was any text sent out
ob_start();
... //code
$str = ob_get_contents();
if (! empty($string))
{
// a warning was thrown.
}
The better way is to define an error handler for warnings and do whatever you want with them:
set_error_handler("my_warning_handler", E_WARNING);
function my_warning_handler($errno, $errstr) {
// do something
}
Set an error handler, and raise exceptions from there. Then catch them as usual.

Categories