简体   繁体   中英

Safest way to parse url for PHP CMS?

As an exercise I am rolling my own CMS to better learn php. Currently I have my .htaccess file set to redirect all URLs to the index.php page.

// .htaccess file 
RewriteEngine on
RewriteRule !\.(js|gif|jpg|png|css)$ index.php

Once I am at the index.php page, I will need to determine what content the user should see based off the requested URL. For example, if the user visited mysite.com/about then I would be including the file contents of about.php .

My question is: what is the safest way to parse this URL for the file value? I want to avoid the user writing malicious URLs which, among other things, could access private php files I don't want shown.

Your htaccess has really nothing to do with security. I suggest you use switch case like this:

$site = "home";
switch(strtolower($_SERVER['REQUEST_URI'])){
  case "about":
    $site = "about";
    break;
  case "contact":
    $site = "contact";
    break;
}
include "{$site}.php";

or maybe this:

$site = "home";
$page = strtolower($_SERVER['REQUEST_URI']);
switch($page){
  case "about":
  case "contact":
    $site = $page;
    break;
}
include "{$site}.php";

Or without having to make list of allowed pages

$path = "pages/";
$page = trim(strtolower($_SERVER['REQUEST_URI']),"/");
$slashPos = strpos($page, "/");
if($slashPos!==false){
    $page = substr($page, 0, $slashPos);
}
$page = preg_replace("/[^a-z0-9-]/", "", $page);
if(file_exists("{$path}{$page}.php")){
    include "{$path}{$page}.php";
}else{
    //include "{$path}home.php";
}

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