PHP: Redirect to different URL

Sometimes you want to redirect a user to the correct URL, such as when the URL change
PHP: Redirect to different URL

Using PHP, it's fairly straight forward to redirect someone and it also quick than doing it through HTML

302 Moved temporarily

If you just want to temporarily move the user, then code 302 is the one for you and not extra definition is needed

header("Location: https://www.example.com/correct/url"); exit;

Inside your PHP code, you will need to add an header with URL to redirect and on the next line, you need to add exit or bots and other applications might ignore the re-direct

301 Moved permanently

If page is permanently moved, then 301 will tell the ones visiting your page that this page have permanently moved and they should always use the new URL

header('Location: https://www.example.com/correct/url', true, 301); exit;

Single VS Double quote

If you're using variables, you'll need to use double quote or it will not work. Single quote works fine if no variable is used

$new_url = https://www.example.com/correct/url; header("Location: $new_url");

We sometimes publish affiliate links and these always needs to follow our editorial policy, for more information check out our affiliate link policy

You might also like

Detecting bots from User Agent
PHP

Detecting bots from User Agent

Run code in background using PHP-FPM
PHP

Run code in background using PHP-FPM

Waking up during the night to pee could mean you're peeing wrong
Health

Waking up during the night to pee could mean you're peeing wrong

Powder vs Liquid vs Capsul Detergent
Cleaning

Powder vs Liquid vs Capsul Detergent

Comments

Sign up or Login to post a comment

There are no comments, be the first to comment.