Dynamic Include Safety

前端 未结 4 1427
一向
一向 2021-01-14 14:05

Is there any way to safely include pages without putting them all in an array?

if (preg_match(\'/^[a-z0-9]+/\', $_GET[\'page\'])) {

$page = $_GET[\'page\'].\".ph         


        
4条回答
  •  北海茫月
    2021-01-14 14:59

    The weakness in your current implementation is that …

    1. the regular expression just tests the beginning of the string, so “images/../../secret” would pass, and
    2. without further validation, “index” would also be a valid value and would cause a recursion.

    To make your implementation safe, it’s a good practice to put everything, that’s intended to be included, in its own directory (e.g. “includes” and “templates”). Based on this, you just have to ensure that there is no way out of this directory.

    if (preg_match('/^[a-z0-9]+$/', $_GET['page'])) {
        $page = realpath('includes/'.$_GET['page'].'.php');
        $tpl = realpath('templates/'.$_GET['page'].'.html');
        if ($page && $tpl) {
            include $page;
            include $tpl;
        } else {
            // log error!
        }
    } else {
        // log error!
    }
    

    Note: realpath returns the absolute path to the given relative path if file exists and false otherwise. So file_exists is not necessary.

提交回复
热议问题