homepage Welcome to WebmasterWorld Guest from 54.204.127.56
register, free tools, login, search, subscribe, help, library, announcements, recent posts, open posts,
Subscribe to WebmasterWorld

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
PDO, error handling
helenp




msg:4640804
 5:40 pm on Jan 28, 2014 (gmt 0)

Hi,
I am doing PDO, and I like it.
However what I dont like is the error handling.
I have been told not to use try and catch in the conection as this is not safe or good, and php should handle the errors.

If i put a false password in the conection I dont get any error message at all, the page just stops to load.
I am on a shared host so there is nothing I can touch except .htaccess.

Also I miss the or die in the query.
When code is wrong there is no error messages at all.
Any suggestions or opinions about the try and catch?
I prefer a personal message to come up, rather than a halfloaded page.

 

penders




msg:4640851
 9:52 pm on Jan 28, 2014 (gmt 0)

I have been told not to use try and catch in the conection as this is not safe or good, ...


Hhhmm, I thought this was the good thing with PDO; the exception handling? What else do they propose to do?

As the manual says:
"PDO::__construct() throws a PDOException if the attempt to connect to the requested database fails."

If you don't use a try...catch block then your "page just stops to load" if there is a connection error - oh wait, hang on! ;)

...and php should handle the errors.


? In what way should it "handle the errors"?

helenp




msg:4640856
 10:07 pm on Jan 28, 2014 (gmt 0)


posts: 2824
msg:4640851new post indicator10:52 pm on Jan 28, 2014 (utc +1)

I have been told not to use try and catch in the conection as this is not safe or good, ...


Hhhmm, I thought this was the good thing with PDO; the exception handling? What else do they propose to do?

As the manual says:
"PDO::__construct() throws a PDOException if the attempt to connect to the requested database fails."

If you don't use a try...catch block then your "page just stops to load" if there is a connection error - oh wait, hang on! ;)

...and php should handle the errors.


? In what way should it "handle the errors"?


If you read the warning for the error handling, there is a risk that password can be put into screen etc.,
also comments says its a really bad thing:
[php.net...]
"Warning

If your application does not catch the exception thrown from the PDO constructor, the default action taken by the zend engine is to terminate the script and display a back trace. This back trace will likely reveal the full database connection details, including the username and password. It is your responsibility to catch this exception, either explicitly (via a catch statement) or implicitly via set_exception_handler()."


This is from another forum, wich I used as a manual, and the guy looks like he know whats he talking about regarding security:
"PDO and MySQLi make this technique obsolete. You can now turn on exceptions and delegate the error checking to PHP. See “Connecting to the database”.

Catching all exceptions
A weird pattern that seems to get copypasted around the Internet and even made it into the PHP manual is to arbitrarily catch exceptions and print the error message on the screen:
This is a terrible idea and doesn't make any sense whatsoever.

First of all, internal error messages are not meant to be shown to the whole world on your public website. They contain technical information for you, the developer. Exposing them will irritate legitimate users and help attackers gather information about your system. So don't do it. Let PHP take care of the error messages. It will send them to the device you've specified in the php.ini. On a production website, error messages go into an error log and must not be printed on the screen. In your local test environment, you may activate display_errors for easier debugging.

Secondly, the “error handling” above is completely useless, because it does what PHP would do anyway. Stopping the script and generating an error message is exactly the default behavior of exception. So what's the point of the code in the first place?

As a simple rule: If you can't solve a runtime error, don't touch it. Just let the exception “bubble up”. Either some other code will take of it. Or the exception will abort the script in a controlled manner."

I dont agree that the message is stupid, I am on a shared host and cant touch php.ini.
And I would like an error code as sometimes sql is down but the web is up and running.

What do you think?

penders




msg:4640874
 11:50 pm on Jan 28, 2014 (gmt 0)

If your application does not catch the exception thrown...


None of that is saying it's "not safe or good" to use a try...catch block. What it is saying is that you need to catch the exception... somehow. Which you can do by either using a try...catch block or setting up a global exception handler (which is possibly what you refer to as "php should handle the errors" or as the guy says "delegate the error checking to PHP"). When an Exception is thrown it bubbles up until it is caught. If it is not caught (and there is no custom error handler) then a fatal error results and a stack trace might be output - that is when your password etc. might be revealed.

If you were to output $e->getMessage() in your catch block then you should not see the password, you would get a message like this (if you used an incorrect password):
"Access denied for user 'user'@'localhost' (using password: YES)"

But, as you've stated above, these errors should not be output to the page anyway on a live site (you won't see them) - they should be written to a secure error log (using a custom error handler / exception handler). However, whilst you are developing the site (on your local test server) it can be useful (ie. quicker) to see these runtime errors output directly to the page - you can see straight away if you have the connection details entered incorrectly.

When an error/exception occurs on a live site (this is after you've already got all the obvious bugs out and it's been working great for a while) you don't want to output the error to the page when some other alien visitor comes along, since it's not going to mean anything to them and you're going to be blissfully unawares. An error might have occurred because there has been a power cut, you've been hacked, someones pressed the wrong button, etc. etc.

If no database connection is a show stopper then you must still catch the exception (somehow) and present a friendly message to the user... eg. "System down for maintenance" (send a 503 and a Retry-After HTTP header). Meanwhile, your error log has all the goo.

You create your own/custom error handler using the set_error_handler() [php.net] function and likewise to create your own exception handler you use set_exception_handler() [php.net]. You can pass a callback to these functions that handle everything, write errors to a log file, send emails, etc. You set this up once at the very start of your application. You don't need to touch php.ini

Some hosts will manage an error log by default, some don't. (But you would still need to ini_set('display_errors','0'))

helenp




msg:4640935
 7:33 am on Jan 29, 2014 (gmt 0)

Thanks,
This should not be used:
"He really says not to use it at all:

"// DO NOT USE THIS! It's is a negative example

try {
$database->do_something();
} catch (PDOException $error) {
die('Dear users of the Internet, this database error just happened on my server: ' . $error->getMessage());
} "

I been checking those error handler pages, and of course dont understand them enough.
But if I understand correctly what you says,
I could use above or the version in php.net:
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}

in my conection but without using $error->getMessage()) if posible to take away, or even better I should write those error message on a log instead of the screen

swa66




msg:4640967
 10:34 am on Jan 29, 2014 (gmt 0)

The issue the author of
"// DO NOT USE THIS! It's is a negative example

try {
$database->do_something();
} catch (PDOException $error) {
die('Dear users of the Internet, this database error just happened on my server: ' . $error->getMessage());
} "

raises is that one should NOT print full error messages to users.

try - catch should be used, just don't print the getMessage().

Users do not understand them, nor do they help them as they can't fix anything anyway.
On the other hand they do tell (a lot of) internal details to attackers.

So how do you handle it instead:
- you create your own logs that reference the "incident" and contain the details for a developer to be able to trace and understand what went wrong.
- you output to the user a "oops something went wrong!, here is an incident number/code"
The code can in its simplest form easily be a line number in the code (__LINE__) and a coded reference to the file.

helenp




msg:4640993
 1:03 pm on Jan 29, 2014 (gmt 0)

try - catch should be used, just don't print the getMessage().


Actually in a thread about PDO I used try and catch, because nothing worked, and was told not to even try the try and catch.
Anyway, I suppose he says as maybe many sucha as me do not understand how to use it properly.

To output the error and not display it,
maybe I should do something like:
try {
$database->conecxion here;
} catch (PDOException $error) {
die('My message here: ' . $errorlog->Output("conexion/error/".$error.".log");
}


Please don´t laugh ;)

Edited, puf,
I forgot to add ->getMessage()) and no idea how and if possible lol

Would have to have a look at this:
You create your own/custom error handler using the set_error_handler() [php.net] function and likewise to create your own exception handler you use set_exception_handler() [php.net]. You can pass a callback to these functions that handle everything, write errors to a log file, send emails, etc. You set this up once at the very start of your application. You don't need to touch php.ini


However I dont mind about any errorlog, just want a message if only mysql is down but not the web.

Suppose not to display the internal message, only my customized I could do:
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: ";
die();

helenp




msg:4641053
 5:34 pm on Jan 29, 2014 (gmt 0)

Wonder if I was drunk ;)

try {
$database->conecxion here;
} catch (PDOException $error) {
die('My message here: ' . $errorlog->Output("conexion/error/".$error.".log");
}

->Ouput is how I do the pdf files,
anyway, something like this maybe?
error_log("$error", 3, "/mylogile.log");




Suppose not to display the internal message, only my customized I could do:
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: ";
die();

Wonder where I copied that from,
meant to just not print it out like this:
try {
$database->do_something();
} catch (PDOException $error) {
die('My error message);
}

penders




msg:4641279
 5:03 pm on Jan 30, 2014 (gmt 0)

The issue the author of

// DO NOT USE THIS! It's is a negative example  

try {
$database->do_something();
} catch (PDOException $error) {
die('Dear users of the Internet, this database error just happened on my server: ' . $error->getMessage());
}


raises is that one should NOT print full error messages to users.


As mentioned, outputting the cryptic error message (in a live environment) is not good. But also, using die() in this way (on a live site) to abruptly terminate your script is not exactly recommended either.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved