duan33360 2015-11-12 11: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 11: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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部