【问题标题】:Generate PHP switch based on folder content根据文件夹内容生成 PHP 开关
【发布时间】:2013-05-09 19:05:18
【问题描述】:

假设我有一个包含 3 个文件的文件夹;文件 1.php、文件 2.php、文件 3.php。 在同一个文件夹中,我有 index.php,我想为每个文件生成 switch case。

$files = array();
$folder = opendir(realpath(dirname(__FILE__)));
while ($file = readdir($folder)) { 
    if (strpos($file, '.php') !== false && $file !== 'index.php') { 
        array_push($files, $file);  
    }
}

$switch = $_GET['component'];
switch($switch) {
    foreach ($files as $file) {
        case str_replace('.php', '', $file):        include_once($file);                break;
    }   
}

我希望我的案例最终看起来像什么:

$switch = $_GET['component'];
switch($switch) {
        case file1:     include_once('file1.php');              break;
        case file2:     include_once('file2.php');              break;
        case file3:     include_once('file3.php');              break;
}

【问题讨论】:

  • 我不确定我是否对您在这里想要实现的长期目标有一个正确的概述......所以......只是为了确认:您有很多文件,并且文件代表组件。根据 URL 中提供的组件,您想要包含不同的文件?而且页面上只能有一个组件,不能有多个组件?

标签: php file loops switch-statement


【解决方案1】:

嗯……我觉得很费解。

if( in_array($_GET['component'].".php",glob("*.php")) && $_GET['component'] != "index")
    include_once($_GET['component'].".php");

【讨论】:

  • +1 给你。如果它真的很好用。但是如果您可以检查$_GET['component'] 的值并检查该文件是否存在,那将是完美的。
  • 谢谢!正是我所需要的,但有一些小改动:)
  • @imsiso 这样不安全,允许访问其他文件,例如../hax.php
  • 好的,但我想说的是关于处理错误以防止将我们的错误数据提供给黑客。
  • @imsiso 如果文件不存在,则不会在glob 数组中,因此无法通过测试。
猜你喜欢
  • 2018-06-27
  • 2016-09-10
  • 2023-03-27
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
  • 2012-11-10
  • 1970-01-01
  • 2017-08-25
相关资源
最近更新 更多