Using 'or die()' to stop on errors in PHP

Asked
Active3 hr before
Viewed126 times

6 Answers

using
90%

PHP error handling using die() function,Custom error handling function,We can use here die() function to prevent above error.,PHP file handling function

< ? php

if (!file_exists("meera.txt")) {
   die("File Not Found !!");
} else {
   $myfile("meera.txt", "w");
}

?
>
88%

load more v
72%

@rjmunro: = is the assignment operator. It's not a function, but in PHP it also takes precedence over the or operator. I just clarified in my edit. – BoltClock ♦ Jul 21 '10 at 12:29 ,In PHP, variable assignment (the equals sign) and functions both take precedence over the or operator. That means a function gets executed first, then the return value of the function is used in the or comparison. In turn when you use two values/variables together with an or operator, it compares the two values first then returns a Boolean value.,Making statements based on opinion; back them up with references or personal experience.,PHP does something often called "type juggling". In other words: PHP transforms the type of any value for the current use case. Since Strings will be transformed to "true" values, your expression returns true. But echo wants to print an string expression and transforms "true" to 1. Kinda annoying in some cases, but if you know it, you also know how to handle ;)

Therefore, the order of evaluation in this example is:

$result = mysql_query($query) or die();

The order of evaluation in this example is:

$name = "John Doe";
echo $name or "Anonymous";
load more v
65%

All these bad practices prevent PHP from telling a programmer what the problem is . And we already learned that error messages are extremely important.,The answer is surprisingly simple: just leave error messages alone,All the confusion is coming from the fact that every site has two kinds of customers: a programmer and a user, who require totally different treatment in regard of error messages:,it it essentially useless for the site programmer/admin as they likely won't be browsing the site at the moment and will have no idea the error has been occurred.

Only as a last resort set them right in the script using ini_set() command:

error_reporting(E_ALL);
ini_set('display_errors', 1);

And such a separation - between a live and a dev server - is the very source of confusion. As a matter of fact, many newbie PHP users are writing their code as though they will always be the only users of their site, bluntly directing error messages right on the screen. Don't you believe me? How many times did you see such a code:

// BAD example! Do not use!$result = mysqli_query($conn, $query) or die(mysqli_error($conn));

or

// BAD example! Do not use!try {    $stmt = $pdo->query($sql);} catch (PDOException $e) {    die($e->getMessage());}

an if operator that checks the function call's result but does nothing in case of error (or outputs some meaningless stuff like "Error!", "Query failed", etc.). Like:

// BAD examples! Do not use!if ($stmt = $mysqli->prepare($query)) {    // ...proceed with the query}// orif ($stmt = $mysqli->query($query)) {    // ...proceed with the query} else {    echo "FAILED";}

Instead, it should be transferred into a PHP error. The simplest way to do so is to use the trigger_error() function:

$result = mysql_query($query) or trigger_error(mysql_error());

Even better would be to throw an exception. The simplest way is just to test the function's result and to add a throw operator (note that you cannot use it neatly with or operator, the condition should be explicit):

if ($error = json_last_error_msg()) {
   throw new\ Exception("JSON decode error: $error");
}

But that's just a quick and dirty solution. The best way would be to create a dedicated Exception class for such an error. It's not a big deal, basically it's just a single line:

class JsonDecodeException extends ErrorException {}

yet after defining the dedicated class we can create a more talkative version of json_decode():

function jsonDecode($json, $assoc = false) {
   $ret = json_decode($json, $assoc);
   if ($error = json_last_error()) {
      throw new JsonDecodeException(json_last_error_msg(), $error);
   }
   return $ret;
}

Now it will start spitting the error telling us the reason, just like expected:

Fatal error: Uncaught exception 'JsonDecodeException'
with message 'Syntax error' in /home/me / test.php: 9 Stack trace: #0 /home/me/test.php(14): jsonDecode('foobar')# 1 {
   main
}
thrown in /home/me / test.php on line 9

Historically, there was only errors in PHP. Then in PHP 5 exceptions were added to the language and since then PHP is moving slowly to replace errors with ErrorExceptions. As this process is not finished yet, we have to deal with two possible kinds of errors - errors and ErrorExceptions. It is not so convenient. Besides, exceptions are more versatile than errors - they could be caught, and they contain a stack trace by default. So consider turning all errors into exceptions, as it will allow the uniform error handling. The code to do so is ridiculously simple:

set_error_handler(function($level, $message, $file = '', $line = 0) {
   throw new ErrorException($message, 0, $level, $file, $line);
});

Add these three lines to your PHP scritps and you'll be able to catch PHP errors! For example, the following code

try {
   $a = 1 / 0;
} catch (Throwable $e) {
   echo "Come on, you cant't divide by zero!";
}

All right, it's OK with a programmer, they are notified of the every error occurred, either from a log file or just by watching the screen. But what about a site user? With proper error reporting set, they will just face a blank page, which is apparently not the way to go. We need to show them some explanations and ask to try later. There are several ways to do that. The simplest way is to configure your web-server to show such a page in case of error. For example, to configure Nginx to show a custom error page in case of 500 error, just create such a custom error page, and then add this line to the server configuration:

error_page 500 502 503 504 / 500. html

Given we already used the error handler function to convert errors to exception, now we need only an exception handler function.

set_exception_handler(function($e) { // here we can put some code to notify a user about an error.});

But having such a function for just a user's convenience will make the programmer unhappy, as the latter wants to see the actual error message. So let's create a universal function that could satisfy both. In order to do so we need some parameter to tell a dev environment from a production one. There are many possible solutions, in my case I would just use the display_errors php.ini configuration parameter. As it must be set to 0 on the production server we could use it to tell that we are in the production environment. But of course you could use your own markers, for example using a constant is very common solution.

set_exception_handler(function ($e){    error_log($e);    http_response_code(500);    if (ini_get('display_errors')) {        echo $e;    } else {        echo "<h1>500 Internal Server Error</h1>              An internal server error has been occurred.<br>              Please try again later.";    }});

Fatal errors are not caught by the standard error handler. To handle them the same way as other errors, we will need another function, register_shutdown_function which will tell PHP to call a function every time the PHP execution is terminated, both of natural causes or in case of error. So we will need to tell the latter from the former, for which the error_get_last() will be used, also providing the error information:

register_shutdown_function(function() {
         $error = error_get_last();
         if ($error !== null) { // here we can put some code to notify a user about an error.    }});

First, we need to configure basic error handling directives in the PHP/web-server configuration as discussed here. Then let's create a file called error_handler.php with the following code inside, and include it in your bootstrap file:

<?phperror_reporting(E_ALL);function myExceptionHandler ($e){    error_log($e);    http_response_code(500);    if (filter_var(ini_get('display_errors'),FILTER_VALIDATE_BOOLEAN)) {        echo $e;    } else {        echo "<h1>500 Internal Server Error</h1>              An internal server error has been occurred.<br>              Please try again later.";    }}set_exception_handler('myExceptionHandler');set_error_handler(function ($level, $message, $file = '', $line = 0){    throw new ErrorException($message, 0, $level, $file, $line);});register_shutdown_function(function (){    $error = error_get_last();    if ($error !== null) {        $e = new ErrorException(            $error['message'], 0, $error['type'], $error['file'], $error['line']        );        myExceptionHandler($e);    }});
load more v
75%

If the $userModel throws an exception, it is caught and the code within the catch block is executed. In this example, the scripts dies, echoing the error message that the UserModel defined.,If you are calling a method that might throw an exception, you can catch that exception using a try/catch block:,This exception is thrown for database errors, such as when the database connection cannot be created, or when it is temporarily lost:,This can be handy for handling the error yourself, or for performing cleanup before the script ends. If you want the error handler to function as normal, you can throw a new exception within the catch block:

throw new\ Exception("Some message goes here");
load more v
40%

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL),Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.

<?php
$conn = mysqli_connect('localhost','root','','khazar');
if(!$conn){
	die("Connection failed!!!").mysqli_error();
}
else{
	echo "Connected succesfully";
}

$sql = "SELECT * FROM students";
$result = mysqli_query($conn,$sql);
if(!$result){
	die("table connection problem!");
}
// listing all datas from table
echo "<h2>List of al records: ".mysqli_num_rows($result)."</h2>";
echo "<table>";
//if(mysqli_num_rows($result)>0){
	while ($row = mysqli_fetch_assoc($result)) {
		echo $row['id']." | ".$row['name']." | ".$row['username']." | ".$row['password']."<br>";
		?>

		<form method="post" action="$_SERVER['PHP_SELF']">
		<a href="f.php? id=<?php echo $row['id']?>">DELETE</a>
		<a href="f.php? id=<?php echo $row['id']?>">EDIT</a>
		<a href="f.php? id=<?php echo $row['id']?>">UPDATE</a>

<!--	}   -->
}
<?php
if(isset($_GET['id'])){
	$id = $_GET['id'];
	$sql2 = "DELETE FROM students WHERE id=".$id;
	mysqli_query($conn,$sql2);
	header("Location:".$_SERVER['PHP_SELF']);
}
mysqli_close($conn);
?>
load more v

Other "using-undefined" queries related to "Using 'or die()' to stop on errors in PHP"