amit amit - 6 months ago 13
PHP Question

PHP page redirect

Can PHP make a redirect call after executing a function? I am creating a function on the completion of which I want it to redirect to a file located in the same root folder. Can it be done?

if {
//i am using echo here
}

else if ($_SESSION['qnum'] > 10) {
session_destroy();
echo "Some error occured.";
//redirect to user.php
}

Answer

Yes, you would use the header function.

header("Location: http://www.yourwebsite.com/user.php"); /* Redirect browser */
exit();

It is a good practice to call exit() right afterwords so that code below it does not get executed.

Also, from the documentation:

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

This means you should not echo anything right before the header() function, as doing so will more than likely throw an error. Also, you will need to verify that this code gets run before any other output as well.

Comments