[php] How to redirect to the same page in 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?

This question is related to php redirect

The answer is


Another elegant one is

header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
exit;

Simple line below works just fine:

header("Location: ?");

A quick easy approach if you are not concerned about query params:

header("location: ./");

header('Location: '.$_SERVER['PHP_SELF']);  

will also work


To really be universal, I'm using this:

$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' 
    || $_SERVER['SERVER_PORT'] == 443) ? 'https://' : 'http://';
header('Location: '.$protocol.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
exit;

I like $_SERVER['REQUEST_URI'] because it respects mod_rewrite and/or any GET variables.

https detection from https://stackoverflow.com/a/2886224/947370


I use correctly in localhost:

header('0');

I just tried using header("Location: "); (without any value) and it redirected to the current page.


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';