简体   繁体   中英

How to use GET & Include to dynamically PHP files from diff directory

I am very new to PHP, just learning it. need help in the code. I have organised my php pages to be included in diff folder - content & security. Now I want to include the pages from these folders using GET and include function in PHP.

Below is my code for including the file: It works fine only for content directory. please let me what I need to change in the index.php code and my menu.php

index.php code:

include "/templates/header.php";
include "templates/menu.php";
include "/templates/splash.php";
// Set the default name 
$action = "home_index"; 
// Specify some disallowed paths 
$disallowed_paths = array('header', 'menu', 'splash', 'bottom_page', 'footer'); 
if (!empty($_GET['action'])) 
{ 
    $tmp_action = basename($_GET['action']); 
    // If it's not a disallowed path, and if the file exists, update $action 
    if (!in_array($tmp_action, $disallowed_paths) && file_exists ("content/{$tmp_action}.php"))
        $action = $tmp_action; 
} 
// Include $action
include "/content/$action.php";  
include "/templates/bottom_page.php";
include "/templates/footer.php";
?>

below is my code for menu.php:

<ul>
            <li class="first current_page_item"><a href="?action=home_index">Homepage</a></li>
            <li><a href="?action=products" title="Products">Products</a></li>
            <li><a href="?action=services" title="Services">Services</a></li>
            \<li><a href="?action=about" title="About Us">About</a></li>
            <li><a href="?action=contact" title="Contact Us">Contact</a></li>

            <?php
            if(isset($_SESSION['username']) && $_SESSION['username']== true){
             echo '<li> <a href="?action=logout">Logout</a></li>';
            }else{
             echo '<li class="last"><a href="?action=login" title="Login Page">Login</a></li>';
             }
             ?>

        </ul>
include "/content/$action.php";  
         ^---

include() works at the filesystem level, and has absolutely NO idea what your site's document root is. Since your include path starts with / , PHP is starting the search for your file at the root of the server's filesystem, not the root of your site.

eg you're doing the equivalent of

include c:\content\$action

when it should be

include c:\path\to\website\document\root\content\$action

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM