Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP using exit()

I am using Cakephp but this is a MVC/php doubt

letting the view display the message

vs

echo 'Invalid Data'; exit;

I would like to know is there any pitfalls in the second case like memory leak etc.. Which one is better

EDIT

In case of a ajax call is exit good. and what about memory leak and other issues . Are all variables deallocated

like image 320
aWebDeveloper Avatar asked Jun 30 '26 11:06

aWebDeveloper


2 Answers

You should use a custom ExceptionHandler (set_error_handler / set_exception_handler) and throw an Exception if you encounter any errors (CakePHP should already provide an ExceptionHandler). Make some space in your view and if the ExceptionHandler/ErrorHandler has a message, show it there to let the user know.

Your second code will just produce a blank page containing the little text. Every user will appreciate if you show the message inside your usual page layout instead of producing a blank page (which looks broken to most people).

like image 163
halfdan Avatar answered Jul 03 '26 00:07

halfdan


The Cake tools to signal errors to the user are session messages and error views.

For "passive" actions like view actions, you should throw a 404 or similar, possibly more specialized error, e.g. if the requested model does not exist:

function view($id) {
    $data = $this->Model->read(null, $id);
    if (!$data) {
        $this->cakeError('error404');
    }

    ...
}

See Error Handling with CakePHP.

For any POST action, you should return the user to the view and display an error message using $this->Session->setFlash('Error!') and appropriate error messages for each invalid form field. That's the default behavior of baked views and controllers.

Terminating the whole script with exit makes for a miserable user experience.

like image 43
deceze Avatar answered Jul 03 '26 01:07

deceze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!