1

I have different mods such as users, statistics and etc. If I click over users I get information about users, if I click statistics I get user statistics and so on. But I want to do that automatically with php (not OOP) - auto include and call files (for example users.php, statistics.php and others) from mods folder. I know php OOP has autoload class function. But I don't know PHP Object Oriented. How can I do that with PHP without OOP? I want links to be like that:

<a href='index.php?mod=users'>User list</a> <a href='index.php?mod=statistics'>Statistics</a>
Pubby
  • 51,882
  • 13
  • 139
  • 180
Someone
  • 736
  • 2
  • 12
  • 29
  • you want to auto include all files from mods folder or du you want to auto include users.php from folder mods if $_GET["mod"] is users? – noob Dec 05 '11 at 08:16
  • @micha I want to auto include users.php from folder mods if $_GET["mod"] is users – Someone Dec 05 '11 at 08:18

2 Answers2

2
if (isset($_GET["mod"]) && file_exists("mods/" . preg_replace("/[^\w\d]+/", "", $_GET["mod"]) . ".php")) {
    include "mods/" . preg_replace("/[^\w\d]+/", "", $_GET["mod"]) . ".php"; // or: require("mods/" . preg_replace("/[^\w\d]+/", "", $_GET["mod"]) . ".php");
}
noob
  • 8,982
  • 4
  • 37
  • 65
  • You need to sanitise the input. What if someone crafted a URL where $_GET['mod'] was ../../../../../../../etc/passwd or similar? Also the difference between include and require is more than just one is more modern than the other. – liquorvicar Dec 05 '11 at 08:55
  • @liquorvicar how can I sanitize input? – Someone Dec 05 '11 at 11:42
  • 1
    @EmilAzizov I sanitize the input directly after liquorvicar reminded me that I should do that. – noob Dec 05 '11 at 11:49
  • @micha I would recommend a "whitelist" style approach to sanitisation. For example, the OP is looking to include files of the form mods/NAME.php. Thus if his php includes only ever include letters and underscores, I would remove all characters except these. – liquorvicar Dec 05 '11 at 12:06
  • If you think it is better, ok. – noob Dec 05 '11 at 12:58
0

Use switch/case or some system of mod sanitation.

// BASE_PATH is some previously defined application path constant

// fetch $mod from $_GET, and if set strtolower() it

switch($mod){
    case 'user':
    case 'admin':
    case 'statistics':
        $path = realpath(BASE_PATH . "/mods/{$mod}.php");
        if(false === $path || !is_file($path)){
            // error, 404?
        }
        require $path;
        break;
    default:
        // invalid mod, 404?
        break;
}

// and so forth
Dan Lugg
  • 20,192
  • 19
  • 110
  • 174