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'] and dirname() 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;
?>
Share:
14,211

Related videos on Youtube

treng
Author by

treng

Updated on June 04, 2022

Comments

  • treng
    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
      Jared Farrish almost 12 years
      I 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 that header("Location: mypage.php") works at all.
    • Zencode.dk
      Zencode.dk almost 12 years
      To redirect to the server root, you could use header('location:'.$_SERVER['HTTP_HOST']);
    • treng
      treng almost 12 years
      @JaredFarrish It doesn't work ,sorry.
    • Jared Farrish
      Jared Farrish almost 12 years
      If 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
      treng almost 12 years
      I got it your code and my code work perfect. Something is wrong with my if..else construction. Redirect doesn't work there