how to include a page in php

末鹿安然 提交于 2021-01-29 10:40:25

问题


I usually use this code below to include the page that I need into the body of my website to include the page when clicking on a link.

<?php
        switch($_GET['page']){

            case '1':
            if(file_exists('main.php'))
            {
        include_once('main.php');
            break;
            }


            default:
        include_once('main.php');
            break;
            }
?>

but then I have to change this everytime i add a menu item by adding a case '2' ... etc and now my question can this be written shorter/dynamically so that i just can add a link without having to change the piece of code everywhere?

ps: i did made it a little bit shorter.. but its still not good enough i think..

i also want to add this: i get my links from a ini file. i place it in there like this:

[navigation] main.php = "Home"

if (!isset($_GET['page'])) {
      $_GET['page'] = 'main.php';

    }
    switch ($_GET['page']){
      case 'main.php':
      case 'about.php':
      case 'portfolio.php':
      case 'tips.php':
        $file = $_GET['page'];
        break;
      default:
        $file = '404.html';
    }
    include_once $file;

is it possible to get this too from the ini file?


回答1:


Try this:

$page = isset($_GET['page']) ? $_GET['page'] : "main.php";
if( file_exists($page)) include($page);
else include("404.html");


来源:https://stackoverflow.com/questions/11520634/how-to-include-a-page-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!