How to redirect to the same page in PHP

前端 未结 9 1670
春和景丽
春和景丽 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: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';
    

提交回复
热议问题