How can I redirect to the same page using PHP?
For example, locally my web address is:
http://localhost/myweb/index.php
How can I redirect within my website to another page, say:
header("Location: clients.php");
I know this might be wrong, but do I really need to put the whole thing? What if later it is not http://localhost/
?
Is there a way to do something like this? Also, I have a lot of code and then at the end after it is done processing some code... I am attempting to redirect using that. Is that OK?
One can use the anchor tag to redirect to a particular section on the same page. You need to add ” id attribute” to the section you want to show and use the same id in href attribute with “#” in the anchor tag.
Now in PHP, redirection is done by using header() function as it is considered to be the fastest method to redirect traffic from one web page to another. The main advantage of this method is that it can navigate from one location to another without the user having to click on a link or button.
Redirection from one page to another in PHP is commonly achieved using the following two ways: Using Header Function in PHP: The header() function is an inbuilt function in PHP which is used to send the raw HTTP (Hyper Text Transfer Protocol) header to the client.
Redirection in PHP can be done using the header() function.
My preferred method for reloading the same page is $_SERVER['PHP_SELF']
header('Location: '.$_SERVER['PHP_SELF']); die;
Don't forget to die or exit after your header();
Edit: (Thanks @RafaelBarros )
If the query string is also necessary, use
header('Location:'.$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']); die;
Edit: (thanks @HugoDelsing)
When htaccess url manipulation is in play the value of $_SERVER['PHP_SELF'] may take you to the wrong place. In that case the correct url data will be in $_SERVER['REQUEST_URI']
for your redirect, which can look like Nabil's answer below:
header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"); exit;
You can also use $_SERVER[REQUEST_URI] to assign the correct value to $_SERVER['PHP_SELF']
if desired. This can help if you use a redirect function heavily and you don't want to change it. Just set the correct vale in your request handler like this:
$_SERVER['PHP_SELF'] = 'https://sample.com/controller/etc';
Another elegant one is
header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"); exit;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With