Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect to the same page in PHP

Tags:

redirect

php

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?

like image 527
user710502 Avatar asked Nov 15 '11 03:11

user710502


People also ask

How do I redirect on the same page?

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.

How redirect same page after submit form in PHP?

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.

How can we redirect page in PHP?

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.

Which PHP function redirect the browser to another page?

Redirection in PHP can be done using the header() function.


2 Answers

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'; 
like image 58
Syntax Error Avatar answered Sep 20 '22 05:09

Syntax Error


Another elegant one is

header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"); exit; 
like image 42
Nabil Kadimi Avatar answered Sep 18 '22 05:09

Nabil Kadimi