Sunday, January 4, 2009

Why exit(); after Header redirect

You'll probably need a few HTTP 302 or 301 redirect in your PHP application when you develop it. To do a redirect, you can easily call:

if(!$valid){
  header($_SERVER['SERVER_PROTOCOL'].' 302 Found');
  header('Location: nextpage.php');
}
unlink('tmp/2A4E22F1.dat');

However, many people do not know that even after this header is called, the code after this line still executes! In the above code, the temporary file "2A4E22F1.dat" is still deleted. Therefore, you must add a exit(); after this redirect.


if(!$valid){
  header($_SERVER['SERVER_PROTOCOL'].' 302 Found');
  header('Location: nextpage.php');
  exit();
}
unlink('tmp/2A4E22F1.dat');

Since it is not valid and you did a redirect, the temporary file is not deleted. This is sometimes what developers miss out when doing redirects. hope it helps!

No comments: