duanlai1855 2017-11-15 13:26
浏览 45
已采纳

PHP安全地包含文件+处理无效参数

I'm having a little problem. I want to securely include files based on the $_GET Parameter from a subdirectory + handle if the parameter is not valid.

 <?php
if(isset($_GET['p']) && $_GET['p'] == 'fahrzeuge'){
        include 'includes/cars.php';
    }
  if(isset($_GET['p']) && $_GET['p'] == 'impressum'){
        include 'includes/impressum.php';
    }
    if(isset($_GET['p']) && $_GET['p'] == 'home'){
            include 'includes/home.php';
        }
      if(isset($_GET['p']) && $_GET['p'] == 'anfahrt'){
            include 'includes/anfahrt.php';
        }
        if(isset($_GET['p']) && $_GET['p'] == 'about'){
                include 'includes/about.php';
            }

?>

This is my Code. Sorry I know it is a noob way of solving this. How can I improve it? Any Suggestions/Help would be highly appreciated

  • 写回答

2条回答 默认 最新

  • doubi4491 2017-11-15 13:44
    关注

    I would use a ternary to set a variable that tells the page what to include.

    This is very similar to Ofir Baruch's answer, except much shorter.

    $pages = array('about','contact','home');
    
    $p = isset($_GET['p']) && in_array($_GET['p'], $pages)? $_GET['p'] : 'home';
    include "includes/{$p}.php";
    

    Basically, you have an array of pages that are possible. In the ternary, we check if $_GET['p'] is set (isset()), AND we check if the value it contains is in the array. If it is, we use $_GET['p'] as $p, if it is not, we set $p to home, this means that home will always be the default if $_GET['p'] is not set, or not a valid page as per the array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型