Archive
This post is archived and may contain outdated information. It has been set to 'noindex' and should stop showing up in search results.
How To Redirect Using PHP
Feb 19, 2010ProgrammingComments (0)
If you've been developing in ASP 3.0 (classic ASP) you may be used to calling the response.redirect() function whenever you need to redirect a user to a different page. You could call this function anywhere in the page, which was convenient. Now that you're using PHP, you may be a little confused about how to redirect. In PHP, you redirect using the header() function and it must be called before any HTML. Like so:

<?php
header('Location: http://www.mysite.com/somepage.php');
exit;
?>
<html>
<body>
Hello world!
</body>
</html>

The function is straightforward. Simply change the URL to the location you want. It will work with relative URLs usually, but it is best to make them absolute. The exit function is also needed as it terminates the rest of the script from running.

A note to the spaghetti programmers out there. This may require quite a change in your coding practices. Perhaps you've read some people recommending that you perform redirects with Javascript so that you can continue to redirect people from within the HTML. That is a bad habit and you should start separating your code from your HTML. Besides, not everyone has Javascript enabled.

Here's a simple use-case showing a basic form input and conditional redirect:

<?php
if ($_POST['btn'] == 'Home') {
header('Location: http://www.mysite.com/index.php');
exit;
}

if ($_POST['btn'] == 'Search') {
header('Location: http://www.mysite.com/search.php');
exit;
}
?>
<html>
<body>
<form method="post">
<input type="submit" name="btn" value="Home">
<input type="submit" name="btn" value="Search">
</form>
</body>
</html>

Keep in mind that you can use PHP to generate a dynamic location to redirect to:

<?php
if (isset($_POST['loc']) && $_POST['loc'] != '') {
header('Location: http://www.mysite.com/article.php?id=' . $_POST['loc']);
exit;
}
?>
<html>
<body>
<form method="post">
<select name="loc">
<option value="1">Article 1</option>
<option value="2">Article 2</option>
<option value="3">Article 3</option>
</select>
<input type="submit" value="Go!">
</form>
</body>
</html>

It's also a good idea to always check for the existence of a variable using it (using the isset function).
Comments (0)
Add a Comment


Please review the commenting policy prior to commenting.
No comments yet