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 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法