如何使用标头定位到不正确的 GET 值的默认位置


How to locate to a default location on incorrect GET value using headers

我试图在收到GET值时将我的php标头定位到特定位置,如果值不正确,它将定位到默认位置,如home.php

这是我到目前为止所做的

<?php
// Check which page is queried
if(isset($_GET['page'])){
    $got = $_GET['page'];
}
else {
    $got = 'home';
}
// Now goto that location
if(header('Location: '.$got.'.php')){
    header('Location: '.$got.'.php');
}
else {
    header('Location: home.php');
}
?>

您可能正在寻找 file_exists() 函数。

你会做这样的事情;

$got = 'home';
if(isset($_GET['page']))
{
  if(file_exists($_GET['page'].".php"))
  {
    $got = $_GET['page'];
  }
}
header('Location: '.$got.'.php');
exit;

编辑最好将允许用户看到的页面列入白名单:

$got = 'home';
$whitelist = array('contact', 'about', 'blog', ...); // could come from your database
if(isset($_GET['page']))
{
  if(file_exists($_GET['page'].".php") && in_array($_GET['page'], $whitelist))
  {
    $got = $_GET['page'];
  }
}
header('Location: '.$got.'.php');
exit;

这可确保只能访问您允许的视图。

if (file_exists( $got . '.php') {
  header('Location: '.$got.'.php');  
} else {
  header('Location: home.php');
}

但最好创建可用页面的白名单,因为此类代码容易受到标头注入的影响。

检查文件是否存在

if (file_exists($got . ".php") 
{
    header('Location: ...');
    exit;
}
else
{
    header('Location: ...');
    exit;
}

显然,您需要确保没有发送以前的标头。

也许你必须使用file_exists?

试试这个,它会在你列入白名单的目录中搜索你所有的PHP页面(动态),然后将其与get请求进行比较,看看该页面是否在你的页面目录中。 如果是,那么它会加载它,否则它会加载你的家.php

$page = array();
$it = DirectoryIterator($dir);
foreach ($it as $page) {
    $pages[] = $page;
}
if (isset($_GET['page']) && in_array($_GET['page'], $pages)
    header("Location: " . $pages[$_GET] . ".php"); // or require_once $page . '.php';
else
    header("Location: home.php"); // or require_once "home.php";

使用 curl 检查请求是否返回 HTTP 200

$http = curl_init($url);
// do your curl thing here
$result = curl_exec($http);
$http_status = curl_getinfo($http, CURLINFO_HTTP_CODE);
if($http_status != 200)
{
    $url = "/home.php";
}
header('Location: '.$url);