一个安全的动态PHP包括?

时间:2012-07-06 14:22:51

标签: php include

如何创建动态PHP包含,这是安全的?例如,我有一个index.php文件,其中包含header.php和footer.php,然后使用

抓取其中的其他页面
index.php?page=about

如果可能,它需要是动态的,因此使用数组和大小写将非常耗时并且需要修改。

我也希望能够根据所包含的页面更改网站标题。

我目前已经有了这个:

<?php
require_once 'includes/config.php';
//Set values for page  
$page_title = 'home page';
$current_page = 'home';

require_once 'includes/header.php';
?>


CONTENT


<?php
require_once 'includes/footer.php';
?>

由于

这是一种安全的方式来包含我的网页吗?

if( isset( $_GET[ 'page' ] ) )
 {
   if( strpos( $_GET[ 'page' ], "/" ) )
     {
      $dir = substr( str_replace( ’’, ”, $_GET[ 'page' ] ), 0, strpos( $_GET[ 'page' ], "/" ) ) . "/";

      $file = substr( strrchr( $_GET['page' ], "/" ), 1 );
      if( file_exists( $dir.$file.".php" ) )
        {
         include( $dir.$file.".php" );
      } else {
         include( "home.php" );
      }
   } else {
      if( file_exists( basename( $_GET[ 'page' ] ).".php" ) ) 
        {
         include( basename( $_GET[ 'page' ] ).".php");
      } else {
         include( "404.php" );
      }
   }
} else {
   include( "home.php" );
} 

2 个答案:

答案 0 :(得分:4)

为防止错误和未经授权的文件访问(安全)到您的网页目录或无效网页以外的网页,您应该执行以下操作。

通过检查期间来验证$ _GET ['page']。虽然句点在文件名中可能有效,但看起来您将从值构造文件名,而句点可能表示尝试获取对根目录的访问权。

从那里我将为include构建文件路径,然后使用file_exists确保它包含之前存在。

至于更改页面的标题,我会做这样的事情:

<?php
$page_title = 'Default Title';
$page_to_include = 'default';

if( strpos($_GET['page'], '.') !== false ){
  //throw/display error - could be a breakout attempt
}
if( !file_exists(sprintf('page_includes/%s.php', $_GET['page'])) ){
  //requested page does not exists, throw or display error
}else{
  $page_to_include = sprintf('page_includes/%s.php', $_GET['page']);
}

//do page validation here with file_exists
ob_start();
include $page_to_include;
$included_page = ob_get_clean(); //gets contents and cleans the buffer and closes it

require_once 'includes/header.php';
echo $included_page;
require_once 'includes/footer.php';
?>

这样首先包含页面并将其存储在缓冲区而不是输出中。它允许您包含页面来修改$ page_title,然后修改后的$ page_title可用于header.php脚本,以便在标记内输出。

答案 1 :(得分:0)

只是为了改变标题?将其添加到header.php

<title>
<?php
if(isset($_GET['page']) {
    echo $_GET['page'];
} else {
    echo 'My Site';
}
?>
</title>