header("Location:/"); redirect works on localhost, but not on remote server
14,211
From the manual:
HTTP/1.1 requires an absolute URI as argument to » Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. You can usually use
$_SERVER['HTTP_HOST']
,$_SERVER['PHP_SELF']
anddirname()
to make an absolute URI from a relative one yourself:
<?php
/* Redirect to a different page in the current directory that was requested */
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/$extra");
exit;
?>
Related videos on Youtube
Author by
treng
Updated on June 04, 2022Comments
-
treng almost 2 years
if (condition) { #lol. Some code here } else { header("Location:/");//i'm trying to redirect to the root }
Redirect works perfectly on localhost, but not on remote server. May be it's all better to use
$_SERVER
? This redirect wouldn't work even if i choose file in the same directory as file with redirect. Hope you help me :)-
Jared Farrish almost 12 yearsI think you need a space:
header("Location: /")
Although, I imagine you're better substituting in an actual URL. Somewhere I seem to remember reading it's a flaw or a bug thatheader("Location: mypage.php")
works at all. -
Zencode.dk almost 12 yearsTo redirect to the server root, you could use header('location:'.$_SERVER['HTTP_HOST']);
-
treng almost 12 years@JaredFarrish It doesn't work ,sorry.
-
Jared Farrish almost 12 yearsIf I had thought it was the answer to the "problem" of using a
/
in a location header, I would have posted it as the answer. The easy way to fix this is to abandon that technique and use a real path. -
treng almost 12 yearsI got it your code and my code work perfect. Something is wrong with my if..else construction. Redirect doesn't work there
-