Question

The code below work like this:

http://www.website.com/?page=home will pull content from http://www.website.com/home.php

-- or --

http://www.website.com/?page=About will pull content from http://www.website.com/About.php

Code:

// Set the default name 
$action = 'home'; 

// Specify some disallowed paths 
$disallowed_paths = array('admin'); 

if (!empty($_GET['page'])) { 
    $tmp_action = basename($_GET['page']); 
    // If it's not a disallowed path, and if the file exists, update $action 
    if (!in_array($tmp_action, $disallowed_paths) && file_exists("{$tmp_action}.php")) 
        $action = $tmp_action; 
} 
// Include $action 
include("$action.php"); 
?>

The code above works fine for all my pages but now I have one custom link which I need to add http://www.website.com/?page=Search to pull the content from http://www.website.com/search/search.php instead of http://www.website.com/Search.php

How can I do that?

Thanks

Was it helpful?

Solution

There are 2 options, you could always look for the file in a sub folder, or you could have a special list of pages with their own paths much like you do with disallowed_paths.

$special_paths = array(
    "search" => "search/search.php",
);

if(in_array($_GET['page'], $special_paths)) {
    $action = $special_paths[$_GET['page']];

This would mean if in future another special page exists with a different path you can simply add it to the array.

Full code would then be:

<?php
    // Set the default name
    $action = 'home.php';

    // Specify some disallowed paths
    $disallowed_paths = array('admin');

    // special paths
    $special_paths = array(
            "search" => "search/search.php",
            "special_b" => "a/different/lengthier/path/file.php",
    );

    if (!empty($_GET['page'])) {
            $tmp_action = basename($_GET['page']);

            // If it's not a disallowed path, and if the file exists, update $action
            if (!in_array($tmp_action, $disallowed_paths) && file_exists("{$tmp_action}.php")) {
                    $action = $tmp_action.".php";
            } elseif(isset($special_paths[$tmp_action])) {
                    $action = $special_paths[$tmp_action];
            }
    }

    // Include $action
    include("$action");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top