Is it possible to redirect a user to a different page through the use of PHP?
Say the user goes to www.example.com/page.php
and I want to redirect them to www.example.com/index.php
, how would I do so without the use of a meta refresh? Possible?
This could even protect my pages from unauthorized users.
Yes it's possible to use PHP, we will redirect to another page, try this one:
There are multiple ways of doing this, but if you’d prefer
php
, I’d recommend the use of theheader()
function.Basically
If you want to kick it up a notch, it’s best to use it in functions, that way, you are able to add authentications and other checking elemnts in it.
Let’s try with by checking the user’s level.
So,suppose you have stored the user’s authority level in a session called
u_auth
.In the
function.php
You’ll then call the function for every page that you want to authenticate.
Like in
page.php
or any other page.I hope you’ll find some of the content useful
References;
1. Using header in-build php function
a) Simple redirect without parameters
b) Redirect with GET parameters
2. Redirect with javascript in php
a) Simple redirect without parameters
b) Redirect with GET parameters
Output JavaScript from PHP using echo, which will do the job.
You can't really do it in PHP unless you buffer the page output and then later check for redirect condition. That might be too much of a hassle. Remember that headers are the first thing that is sent from the page. Most of the redirect is usually required later in the page. For that you have to buffer all the output of the page and check for redirect condition later. At that point you can either redirect page user header() or simply echo the buffered output.
For more about buffering (advantages)
What is output buffering?
Don't forget to die()/exit()!
This is regular and normal PHP redirect but you can make a redirecting a page with few second wait below code: