【问题标题】:How to redirecting page if user directly entered page name in URL如果用户直接在 URL 中输入页面名称,如何重定向页面
【发布时间】:2017-10-28 18:51:27
【问题描述】:

如果用户在 URL 中输入页面名称,我必须重定向页面。我有两个页面分别称为 index.php 和 shop.php

在 index.php 页面中有一个名为<a href="shop.php?function=add">Click here</a> 的链接。如果我点击链接,则页面将正确重定向到 shop.php。

现在的问题是,如果任何用户直接在 URL 上输入 shop.php,则该页面应重定向到 index.php 页面。这意味着用户将无法直接访问 shop.php 页面。

我不是在说header('location')

【问题讨论】:

  • 使用isset 检测GET 请求。例如,如果 isset($_GET['function']) 然后做某事(显示页面),否则 - die() 或某事(显示错误等)
  • 如果$_GET 为空或无效,为什么不能使用header() 重定向?你也在使用框架吗?
  • Charlietfl 先生,我试过 if (!isset($_GET['function'])) { header("Location: index");出口;如果任何用户输入 shop.php 但我的链接不起作用,页面也会重定向。意味着它也在 index.php 页面上重定向
  • 请澄清,如果用户尝试访问shop.php?function=add会发生什么?
  • Mr.Abhijit,我必须从链接中运行添加功能,而不是直接运行。

标签: javascript php html .htaccess url


【解决方案1】:

我认为,您应该尝试以下方法:

if(isset($_GET['function']) && $_GET['function'] == 'add') {
    // Show page contents
}
else {
    header('location: index.php');
}

【讨论】:

  • Mr.bor32,我试过你的代码。但链接也在 index.php 页面上显示
  • @NarendraVerma 如果您不将?function=add 设置为您的网址,您将转到主页。这不是你想要达到的目标吗?
  • 但它应该可以工作。您是否总是使用查询“function=add”调用 shop.php 页面?
  • 是的,我必须始终调用页面 shop.php?function='add'
  • 嗯。请不要将查询字符串设置为“”。只需致电:shop.php?function=addadd 不等于 'add'
【解决方案2】:
if(isset($_GET['function'])) {
    if($_GET['function'] == 'add'){
        // Show page if function is "add"
    }
    else {
      // "Function" is not "add", it can be anything else: "remove", "edit", etc.
    }
}
else {
    header('location: index.php');
    exit();
}

如果你不想使用header('location: index.php');,你可以使用。

?>
<script type="text/javascript">
    window.location.href = 'index.php';
</script>
<?php

$URL = 'index.php';
echo '<script type="text/javascript">document.location.href="' . $URL . '";</script>';
echo '<meta http-equiv="refresh" content="0; url=' . $URL . '">';

【讨论】:

  • 真的吗? $_GET("function")?
  • AdhershMNair 先生。它将是 $_GET ["function"]
  • 抱歉已修复。谢谢。
【解决方案3】:

你应该尝试在会话中添加一个随机字符串

 <?php 
 session_start();
$random = bin2hex(random_bytes(32));
$_SESSION['random'] = $random;
 echo '<a href="shop.php?function=add&token='.$random.'">Click Here</a>';
?>

然后通过将其添加到顶部的 shop.php 来检查

if(!isset($_GET['token']) || $_GET['token'] != $_SESSION['random']){
header('Location : index.php');
}

这样用户就无法直接访问页面了

【讨论】:

    【解决方案4】:

    最后,我找到了解决方案。我不知道我的代码格式是否正确,但我的问题得到了解决。

    我从这里更改链接

    <a href="shop.php?function=add">Click here</a>
    to
    <a href="shop.php?function=add&p_id=1">Click here</a>
    

    并在 shop.php 中添加以下代码

    if ( !($_GET['function']='add' && $_GET['p_id'])){
        header("Location: index.php");// send to login page
       exit;
    }
    

    如果有什么问题请指教。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-13
      • 2022-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多