r/PHPhelp • u/Legal_Revenue8126 • Dec 17 '25
Solved Die/Exit Usage Best Practices?
I have some cases in my code where I utilize the die/exit function to kill the program as a means to throw an error message to a user and prevent unauthorized access to content. People seem to say to just avoid these functions altogether and just throw an exception, but that doesn't make sense to me in this situation.
For example, the following code:
if(!isset($_SESSION['loggedin'])){
echo "Unauthorized Access<br><br>Please <a href='userlogin.php'>Log In</a>";
exit(1);
}Would this be considered good practice, or is there a more ideal way to handle this?
Should I just auto-redirect to the login page instead?
5
Upvotes
7
u/colshrapnel Dec 17 '25
It all depends on the nature of your code. In case it's just basic plain PHP that doesn't follow any standards or good practices, it would be all right.
However, such empty pages, that don't even share the site design, look ugly and unprofessional. If you'd like to make them to match the site design, you can have an distinct script called error.php, which, being included, displays the error message and dies. So all you need is to assign the error message to a variable and then include this page.
5
u/SZenC Dec 17 '25
Oh god no, this way there's no way to add cleanup logic. Either use a middleware based approach, or throw/catch an exception
5
u/HolyGonzo Dec 17 '25
Best way is to probably learn a framework like Laravel that will handle this for you, but if you don't want that and would prefer to custom-code it...
First thing is to note that in a web environment, the exit() code is almost always ignored. So exit(1) and exit(123) and die() will typically behave exactly the same. The exit() statement is usually more for PHP shell scripts.
Second, best practice is usually to use header('Location: your_login_url"); die(); to redirect to the login screen automatically. Otherwise, you're forcing the user to take more one step (click on your link) to log in.
Third, throwing exceptions isn't usually the ONLY component. You usually have some code at the very top that is watching for exceptions and can say "i received an exception indicating the user is not logged in, so I will redirect them with header()". That way there is one central place where your redirect code is managed. When other pieces of code run into a not-logged-in problem, they don't have to each replicate the redirect - they just throw an exception that bubbles up to the top and they let the code at the top handle it.
6
u/nowtwrongbout Dec 17 '25
It's about separating concerns. The purpose of your code is to check if the user is signed in, it shouldn't care about what message is displayed or where it's displayed. Throwing an exception allows for this by delegating the handling to somewhere else.
2
u/LordAmras Dec 17 '25
The reason is considered "Bad Practice" is because the more complex your code is, the harder it becomes to know where your code stops and the more complex is dealing with things you want to do before the end of the script (logging, or general cleanup tasks)
In a modern framework with routing, you should never just exit the script, but throw an exception so that your exception handling system will show the correct page/message to the user.
The advantage of doing that is that if you always know where your script start and end.
Let's say you want to have a system that will log some information of unauthrozed accesses.
If you do exit, you will have to look around all your exit in your codebase, check if they are unauthorized access and add a call to each one to the system that will log the unauthorized access.
With excepction handler you know that all unauthrized accesses will reach that single point so you just have to add it once.
2
u/YahenP Dec 17 '25
The Wordpress way. The most popular CMS is written exactly this way. In any unclear situation, wp_die();
Is this a good idea? It depends.
In small scripts with a linear algorithm without multi-level business logic, this is perfectly fine. In the shitty sites , where business logic is spread thinly over random files (hello, typical WordPress sites built by outsourced agencies), this is often the only possible option.
As for fully-fledged programming architectures with separated business logic, in principle, there never arises a situation where it is necessary to write an exit statement or anything like that. I don't recall writing an exit statement anywhere other than WordPress in the last 10 years. There's simply no need.
1
u/Big-Dragonfly-3700 Dec 17 '25
The best solution for the specific case of a login requirement, is to integrate the login operation on any page the needs it (like the forum software you are posting this on does.)
If a user visits a page without being logged in, the content that is produced and output, in a complete html document, includes any access message and a login button or the actual login form. When the user successfully logs in, they are already on the page they navigated to. If the logged in user then doesn't have permission to access the specific page, the content that is produced and output in the html document would have a message stating so, and the navigation on the page would allow them to go to page(s) that they are authorized to access. If the logged in user does have permission to access the specific page, the content that is produced and output in the html document is whatever that page is designed to do.
This is all just conditional logic that determines what post method form processing code is present/enabled and what content is produced and output in the html document for a page.
1
u/dietcheese Dec 21 '25 edited Dec 21 '25
You don’t want to use exit() in your presentation layer. (“print this HTML”)
If the user is unauthenticated and the right action is “log in,” redirecting is usually the most ideal UX. (Use a 403 only when the user is logged in.)
0
u/martinbean Dec 17 '25 edited Dec 17 '25
You’ve mentioned it yourself: throw an exception. If the user is unauthorised then there’s your exception:
You can then catch this exception in an appropriate place and return whatever response you need to.
EDIT: Since my initial comment didn’t meet u/colshrapnel’s standards, the “appropriate place” I refer to would be your application’s global error handler. Your application should have some code that acts as a “last chance” to handle any uncaught exceptions and errors thrown by your application, and then outputs an appropriate response. You can use PHP’s built-in
set_exception_handlerfunction to define a function that will be used to handle uncaught exceptions. If it’s a HTTP request, you can return a templated error page (instead of echo-ing a HTML string). If it’s a CLI request, then this is where you would print an error message and exit with the exit code (1or greater) that best describes the condition.0
u/guestHITA Dec 17 '25
Best approach dont use outside of testing learning. Lets say you have a very small site and you detect a malicious input then i guess you could just do die or exit, but in reality youd want to log the attack so you can monitor whats happening and present a non descript 404 error page. Thats not even much work tbh.