【问题标题】:Redirect page based on lack of a URL parameter or if parameter is null- PHP根据缺少 URL 参数或参数是否为空来重定向页面 - PHP
【发布时间】:2014-03-31 11:50:35
【问题描述】:

我有一个网址,例如http://foo.com?stone=yes

指向该 URL 的页面是用 PHP 编码的。

我可以用下面的来读石头。

如果满足以下条件,我希望能够重定向页面:

  1. 石头的值为空
  2. 网址中没有石头。

我尝试了以下方法,但没有成功。

 $stonevar = $_GET['stone'];

 if ($stonevar = "") {
    header("Location: http://google.com");
 }

【问题讨论】:

    标签: php url redirect if-statement url-parameters


    【解决方案1】:

    您可以通过empty() 做到这一点

    <?php
    
    if(empty($_GET['stone'])) {
        header("Location: http://google.com");
        exit;
    }
    
    ?>
    

    【讨论】:

    • 不客气。我一注意到你修复了我的评论就删除了。
    【解决方案2】:

    您的代码中有一些错误。

    1- 如果您不检查 $_GET['stone'] 是否存在,您将收到如下警告:Undefine variable...

    2- 在您的 if 语句中,您正在分配一个值,要比较值,请改用 == 或 ===。

    将您的代码更改为:

    $stonevar = isset($_GET['stone']) ? $_GET['stone'] : NULL;
    
    if (empty($stonevar)) {
      header("Location: http://google.com");
      exit();
    }
    

    有用的链接:

    isset

    empty

    Comparison Operators

    Ternary Operator

    【讨论】:

      【解决方案3】:

      if 条件中的代码$stonevar = "" 将值“”分配给变量$stonevar。

      为了比较,您将需要使用相等运算符==,例如:

       if ($stonevar == "") {
       header("Location: http://google.com");
        }
      

      【讨论】:

        【解决方案4】:
        <?php
        
        if(empty($_GET['stone'])) {
        header("Location: http://google.com");
        }
        ?>
        

        【讨论】:

        • 请通过添加不仅仅是代码 sn-p 来提高此答案的质量。
        猜你喜欢
        • 1970-01-01
        • 2013-10-01
        • 1970-01-01
        • 2016-07-05
        • 2018-06-19
        • 2013-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多