How to redirect to the same page in PHP
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;
There are a number of different $_SERVER
(docs) properties that return information about the current page, but my preferred method is to use $_SERVER['HTTP_HOST']
:
header("Location: " . "http://" . $_SERVER['HTTP_HOST'] . $location);
where $location
is the path after the domain, starting with /
.
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
header('Location: '.$_SERVER['PHP_SELF']);
will also work