Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the die() or exit() function needed in the end of a php script?

Tags:

php

In a php script I have some test and after the script the html page.

When a test fail i call die("Test 1 failed"); If no test fail the php script reach the end ?> and then load the html code after the php script.

Is this a good procedure? Or I need to write die() or exit() before the end of php script?

like image 800
newtphp Avatar asked Dec 16 '13 11:12

newtphp


People also ask

How do I end a PHP script?

The exit() function in PHP is an inbuilt function which is used to output a message and terminate the current script. The exit() function only terminates the execution of the script. The shutdown functions and object destructors will always be executed even if exit() function is called.

What does die () do in PHP?

die() function in PHP The die() function prints a message and exits the current script.

Does die () and exit () functions do the exact same thing?

The die() and exit() functions do the exact same thing. There is no difference between die and exit in PHP. Both exit and die are language constructs that output a message and terminate the current PHP script. The difference between die() and exit() in PHP is their origin.


1 Answers

No you don't have to write that and this is not best practice. If the script reaches the end without fatal errros it will exit.

If this means "testing" for you, you're wrong. Testing should be done using unit tests. For php there is phpunit. Give it a try, that's the proper way of testing your code.

Edit: As CompuChip says in a comment, the only useful use case for exit is when you're writing a php based shell script that should return an error code. See the parameter section of the documentation for the exit() function.

like image 187
floriank Avatar answered Sep 19 '22 11:09

floriank