Redirecting a user with php as simple as your first php hello world ! Within the new few minutes you will get to know how to do a php redirect with just s few lines of code.
With these 3 methods you will get to know how to redirect a user or in technical terms forward an http request to another URL with custom response code.
Without wasting more time let’s dive into the code. We will be learning how to redirect to url with these two examples –
But to before looking at these examples you first need to know about the php header function.
Table Of Contents
PHP Header Function
To redirect a user with php we will have to use the php header function . If you don’t know what the header function does it basically sends a raw http request to the client.
NOTE : The header functions needs to be called before any output is sent by your php code to the browser.
Now that you know about the header function let’s see the examples –
PHP Redirect Examples
#1 – Simple Redirection
For redirecting the user to another page you can simply use the following code –
TIP : You can also pass get variables to page like this page-to-redirect.php?attr1=val1&attr2=val2
The Location address can also be a absolute or full URL.
#2 – Making A Temporary / Permanent PHP Redirect
You don’t really need to know about this if you don’t really care about SEO but, if you do care about SEO it’s super important for you to know this.
There are two types of redirects –
- 301 Permanent Redirect
- 302 Temporary Redirect
As you have seen about if you want to redirect permanently you have to use the 301 http status and if it’s a temporary redirect you need to use 302 http code.
301 Permanent Redirect –
header('Status: 301 Moved Permanently', false, 301); header('Location: redirected-page.php'); exit();
302 Temporary Redirect –
header('Status: 302 Moved Temproraily', false, 302); header('Location: redirected-page.php'); exit();
Why To Use The exit() ?
The issue is that even if you redirect the visitor with the header function all the code after the header function gets executed so to prevent the further code from being executed.
So that’s why you need to use exit() or die() to prevent the code from running.
Yeah ! I hope you found all that you needed If you think there should also be some more info
HINT : You can also use this to hide actual file downloading URL.