1

我试图在接收到 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');
}
?>
4

6 回答 6

4

您可能正在寻找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;

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

于 2012-06-11T11:01:29.440 回答
1
if (file_exists( $got . '.php') {
  header('Location: '.$got.'.php');  
} else {
  header('Location: home.php');
}

但最好创建一个可用页面的白名单,因为这样的代码容易受到标头注入的攻击

于 2012-06-11T11:00:32.717 回答
1

检查文件是否存在

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

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

于 2012-06-11T11:02:29.987 回答
0

试试这个,它会在您白名单(动态)的目录中搜索您的所有 php 页面,然后将其与 get 请求进行比较,以查看该页面是否在您的 pages 目录中。如果是,那么它会加载它,否则它会加载你的 home.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";
于 2012-06-11T11:09:24.940 回答
0

也许您必须使用file_exists

于 2012-06-11T11:00:59.943 回答
-1

使用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);
于 2012-06-11T11:02:22.703 回答