How to redirect to the same page in PHP

前端 未结 9 1645
春和景丽
春和景丽 2020-12-01 03:46

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 r

相关标签:
9条回答
  • 2020-12-01 04:00

    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 /.

    0 讨论(0)
  • 2020-12-01 04:05
    header('Location: '.$_SERVER['PHP_SELF']);  
    

    will also work

    0 讨论(0)
  • 2020-12-01 04:06

    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';
    
    0 讨论(0)
  • 2020-12-01 04:06

    I use correctly in localhost:

    header('0');
    
    0 讨论(0)
  • 2020-12-01 04:16

    Another elegant one is

    header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
    exit;
    
    0 讨论(0)
  • 2020-12-01 04:21

    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

    0 讨论(0)
提交回复
热议问题