duan33360 2015-11-12 19:02
浏览 28
已采纳

PHP获取目录中的所有文件名以进行页面切换

Right now I have all my pages under a switch case for when a visitor uses whatever.php?p=pagename

Here is how it is currently

switch($page)
    {
        case 'about':
            include('pages/about.php');
            break;
        case 'contact':
            include('pages/contact.php');
            break;
        case 'edb':
            include('pages/edb.php');
            break;
        case 'eluna':
            include('pages/eluna.php');
            break;
        case 'mercsys':
            include('pages/mercsys.php');
            break;
        case 'pastebin':
            include('pages/pastebin.php');
            break;
        case 'projects':
            include('pages/projects.php');
            break;
        case 'sites':
            include('pages/sites.php');
            break;
        case 'soon':
            include('pages/soon.php');
            break;
        case 'sqlgen':
            include('pages/sqlgen.php');
            break;
        case 'wcms':
            include('pages/wcms.php');
            break;
        case 'add':
            include('pages/add.php');
            break;
        case 'edit':
            include('pages/edit.php');
            break;
        case 'delete':
            include('pages/delete.php');
            break;
        case 'moveAnnouncement':
            include('pages/moveAnnouncement.php');
            break;
        default:
            include('pages/404.php');
    }

My question is, How can I shorten this down to a foreach loop and use the page names for each .php in the pages/ directory without having to add each individual one or any future pages?

  • 写回答

1条回答 默认 最新

  • douzi7711 2015-11-12 19:13
    关注

    upd: like @svrnm adviced, you can do some security checks if you not did it before:

    $filename = realpath('pages/' . $page . '.php');
    if($filename && file_exists($filename)) {
        include($filename);
    }
    

    or/and you can build files whitelist first:

    $whitelisted = glob("*.php");
    if(in_array($page . '.php', $whitelisted) && file_exists($filename)) {
        include($filename);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化