Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do I need to use exit after header("Location: http://localhost/...");?

Tags:

validation

php

I'm creating a script to validate a form and I was asking myself a question. When I use a header (see example below), do I need to use exit right after? I mean, does using header also means that it is exiting by default therefore I don't need to use the command exit?

// cancel button clicked
if (isset($_POST['cancel'])) {
  header("Location: http://localhost/admin/tracks.php");
  exit;
}

echo '<p>$name</p>'
like image 823
Marco Avatar asked Apr 03 '11 05:04

Marco


1 Answers

You should call exit() because a header() won't automatically stop the script from executing - or if it does (I'm honestly not 100% on that), it definitely doesn't stop the script instantly.

For example, try this code:

<?php

  header("Location: http://www.google.com");
  unlink(__FILE__);

?>

This little script uses header() to redirect you to Google, and then deletes itself. If you run it, you'll notice that after you were redirected, the file was still deleted. This means that the unlink() call was still executed even though the header() call redirected you.

like image 89
AgentConundrum Avatar answered Sep 27 '22 23:09

AgentConundrum