PHP: Redirect to different URL

PHP: Redirect to different URL

Sometimes you want to redirect a user to the correct URL, such as when the URL change

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

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

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

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

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

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



Tags: #Redirect #302 #301

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

Comments

Sign up or Login to post a comment

There are no comments, be the first to comment.