我如何保护PHP代码?

时间:2014-11-08 01:25:31

标签: php file upload

我如何保护此代码?

问题是您可以使用../来移回目录。我该如何锁定目录?

<?php
    $target_path = "user/";
    $username = basename( $_POST['user'] );
    $file = basename( $_FILES['file']['name']);
    $target_path = $target_path . $username
    $target_path = $target_path . "/"
    $target_path = $target_path . $file
    if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['file']['name']). " has been uploaded";
?>
<br />
<?php
    echo "The file can be opened or downloaded at asasse.no-ip.org/user/" . $_POST['user'] . "/" . basename( $_FILES['file']['name']);
    } else{
    echo "There was an error uploading the file, please try again!";
    }
?>

1 个答案:

答案 0 :(得分:0)

正如我在评论中提到的那样,使用

$file = "../libs/somebadfile.php"
$file = basename( $file );
//outputs "somebadfile.php"

$path_parts= pathinfo( $file );

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; 

//outputs 
//=========
// "../libs"  - not sure about this can't test it right now ;-p
// "somebadfile.php"   ~ equivalent to basename() above.
// "php"
// "somebadfile"

然后提供基本路径,仅允许用户提供文件名部分。

"path/to/folder" . $file;

没有更多的目录遍历。这也被称为&#34; dot-dot-slash&#34;攻击。来自维基百科

http://en.wikipedia.org/wiki/Directory_traversal_attack

它更好&#34;安全&#34;现在但它可以清理一下:

$basepath = "user/";
$username = basename( $_POST['user'] ) . "/";
$filename = basename( $_FILES['file']['name']);
$filepath = $basepath . $username . $filename;
if(move_uploaded_file($_FILES['file']['tmp_name'], $filepath)) {
    echo "The file can be opened or downloaded at asasse.no-ip.org/$filepath";
}else{
    echo "There was an error uploading file \"$filename\", please try again!";
}

如果您只想允许特定扩展名集的文件,例如图片。

$basepath = "user/";
$username = basename( $_POST['user'] ) . "/";
$allowed = array('jpg', 'png', 'gif', 'bmp' );
if( !preg_match( "/\.(".implode("|", $allowed).")$/i", $filename, $extension ) ){
    echo 'Extension "'.$extension[1].'" not allowed, must be one of the following "'.implode('", "', $allowed).'" file types.';
}else{
    $filename = basename( $_FILES['file']['name']);
    $filepath = $basepath . $username . $filename;
    if(move_uploaded_file($_FILES['file']['tmp_name'], $filepath)) {
        echo "The file can be opened or downloaded at asasse.no-ip.org/".$filepath;
    }else{
        echo "There was an error uploading file \"$filename\", please try again!";
    }
}

P.S我还没有对此进行过测试,但它应该非常接近。