What is the correct way to exit or end a php script if a particular process fails

Hi
Occasionally, believe it or not, one or more lines of my code fails - not due to a syntax error but some other unexpected or possibly predicted event. For example

$mysqli = new mysqli($host,$user,$password,$database);

or

if ($stmt->execute()){
				echo 'Congratulation, your account has been created<br>';
			}
			else {
				echo 'Sorry, there was a problem creating your account - please contact site admin<br>';
				
			}

When a failure occurs, can I use die("Houston we have a problem"); or exit("Oops! Here we go again");

Or is there a more approved method. I am particularly worried about leaving connections open, sessions set, statements created or any other values created or processes running that should be terminated.

Thanks in advance guys

When a php script ends, normally or due to a fatal runtime error, all resources and memory used by that script is destroyed.

OK, thanks, but is using die() or exit() considered ‘normal’ and is it acceptable practice to use them, I have read that they should be avoided ?

In general. you should output a complete, valid web page, i.e. don’t use exit/die statements.

The only times you need an exit/die statement, to halt php code execution, are when YOU want to stop php from running. Some examples -

  1. After a redirect.
  2. When you have determined that the current user is not logged in or doesn’t have permission to access a page.
  3. When you make an ajax request to a combined page that outputs a complete page when requested normally and outputs only data or part(s) of the page in response to the ajax request.

Do you have specific examples you want someone to comment on? And if you are asking about the cute messages you showed, no, those don’t provide a good User eXperience (UX.)

The cute error messages were just generic, tounge in cheek examples for the purpose of my post and I would not display those to a user.

I don’t really have a specific example as I have many areas where I would like to manage errors, but I guess the two above would be good general examples ie exiting a script when a connection fails or more particularly when a prepared statement fails to execute. I would like to exit in a controlled manner and control any error messages so as not to provide detailed messages that could provide security loopholes.

The general principle is to run ob_start at the very beginning of a request so you prevent outputting anything until you’re sure the output will be okay.

Then you’d register a custom error handler and exception handler and when they trigger first destroy the output buffer and render a generic error page, along with the correct HTTP status code, e.g., 500 for internal server error.

If nothing wrong happend you echo ob_get_clean() to output the actual content you know is correct (since the error handlers didn’t trigger).

The only database errors that a visitor to a site can recover from are when inserting/updating duplicate or out of range data that they themselves submitted, where they can resubmit a different value that would be successful. In all other cases, the visitor cannot do anything about a database error and doesn’t need to even know that a database error has occurred (hackers love it when you provide feedback when they intentionally do things that trigger errors.)

To handle both of these cases, simply use exceptions for database statement errors, and in most cases let php catch and handle the exception, where php will use its error related settings to control what happens with the actual error information (database statement errors will ‘automatically’ get displayed/logged the same as php errors - on a live/public site, you would be logging all php errors, which will now include the raw database errors.) The exception to this rule is for inserting/updating of duplicate or out of range user submitted data. In this case, your code would catch the exception, test if the error number is for something that the user can recover from, and setup a message telling the user what exactly was wrong with the data that they submitted. For all other error numbers, simply rethrow the exception and let php handle it.

Thanks to all for your feedback, as usual - most helpful and informative. In hindsight, in this situation, I think I have to have more faith in my code (which means more thorough testing) since after re-thinking, the errors I am trying to manage are not user recoverable but system errors. For instance, in the above examples I am using my own connection parameters and the inputs that are used to populate the prepared statements variables are already parsed.

I think I am being too clever and trying to predict possible system / code failures and present a meaningful message rather than a system error. No matter how accurate my code is and how well parsed the user input, system errors can still occur and I cannot predict all of them.

1 Like