【问题标题】:Redirect to home.php if $_GET['id'] is INVALID. PHP [duplicate]如果 $_GET['id'] 无效,则重定向到 home.php。 PHP [重复]
【发布时间】:2021-01-24 02:32:40
【问题描述】:

我正在尝试重定向用户,因此如果他们在 url 中输入无效的 GET['id'],他们将被重定向到主页。

注意:当 GET 为空时,我已经使用下面的代码使其工作

} else if (empty($_GET['id'])) {
      header("Location: home.php");
      exit;
}

但我的 URL 仅将整数作为 'id' :

website/edit.php?id=10

如果用户输入了一个字母,我想要重定向到主页:

website/edit.php?id=g

这可能吗?感谢您的宝贵时间!

【问题讨论】:

标签: php database url redirect get


【解决方案1】:

如果用户没有在url中提交id参数,empty($_GET['id'])会返回false,因为找不到$_GET[ 'id'] 而不是因为 $_GET['id'] 为空。

如果你想提高准确性,我建议你使用isset函数而不是empty。这也可以避免在你的调试环境中出现类似“Notice: Undefined index: id in abc.php in line 1”的提示。

} else if (isset($_GET['id']) && is_int($_GET['id'])) {
      header("Location: home.php");
      exit;
}

即便如此,如果您可以确定生产环境中没有系统消息提示,您也可以使用 is_int($_GET['id'])。

} else if (is_int($_GET['id'])) {
      header("Location: home.php");
      exit;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多