这可以吗?基于Variable + header redirect执行一次PHP?

Bor*_*aka 1 php wordpress

我正在尝试做的是一个秘密链接,例如website.com/?secret=yes,当他们访问此页面时我想从URL中删除此变量,所以我有以下内容:

<?php
if(isset($_GET['secret']) && $_GET['secret'] === 'yes') {
    header('Location: http://website.com');
    $secret="yes"; <--take note this is what I'm testing 
}
?>
Run Code Online (Sandbox Code Playgroud)

上面的代码会立即重定向,所以url中没有变量,我试着用$ secret ="yes"自己制作这个变量; 能够使用以下代码:

<?php if( 'yes' === $secret ) : ?>
secret content here
 <?php endif; ?>
Run Code Online (Sandbox Code Playgroud)

这可能吗?如何让我的代码工作?我不想使用会话,因为我希望它只执行一次,或者每次通过秘密链接访问时,如果他们访问没有它不显示.

Tim*_*ers 5

不,那不行.变量不会通过重新加载页面而持久存在.但是,您可以使用会话或cookie来执行此操作:

<?php
session_start();
if(isset($_GET['secret']) && $_GET['secret'] === 'yes') {
    $_SESSION['secret']="yes";
    header('Location: http://website.com');
    exit();
}
?>

<?php if( $_SESSION['secret']=='yes'){ 
unset($_SESSION['secret']); //unset so when the page reloads the secret data will be gone
?>
secret content here
 <?php } ?>
Run Code Online (Sandbox Code Playgroud)

  • 会话+1.用户完全不知道Session变量中的内容,只是某处有一个.在设置位置标题后,不要忘记`die()`或`exit`,理想情况下,为了便于阅读,`$ _SESSION ['secret'] ='yes'`应该在`header()`之前. (3认同)
  • 在设置会话变量之后,您可能还想要`exit;`以确保在不应该执行以下代码时执行. (3认同)