简体   繁体   English

PHP中的扩展验证

[英]Extension validation in php

I've been trying and retrying at this code trying to get the file extension and conditionally check against it, but due to the files placement in flow I can't see what's going into $ext. 我一直在尝试并尝试使用此代码来尝试获取文件扩展名并有条件地对其进行检查,但是由于文件放置在流中,所以我看不到$ ext发生了什么。

Can anyone pinpoint what is going wrong here? 任何人都可以查明这里出了什么问题吗? It's just manipulating the uploads file for dropzone.js. 它只是为dropzone.js处理上传文件。

if (!empty($_FILES)) {

    $tempFile = $_FILES['file']['tmp_name'];          //3             

    $targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;  //4

    $targetFile =  $targetPath. $_FILES['file']['name'];  //5

    $ext = end(explode(".", $_FILES['file']['tmp_name']));

    if(filesize($tempFile) < 6000000 and $ext == "png"){
        move_uploaded_file($tempFile,$targetFile); //6
    }

}

You are using tmp_name variable to get extension which will always give you file with .tmp extension. 您正在使用tmp_name变量获取扩展名,该扩展名将始终为您提供扩展名为.tmp的文件。

In place of 代替

$ext = end(explode(".", $_FILES['file']['tmp_name']));

Use this : 用这个 :

$ext = end(explode(".", $_FILES['file']['name']));

Update :- But it is better to validate the file type by checking its mime time(as said by @castis), as some user might rename its file with some extension and upload it. 更新:-但是最好通过检查其mime时间来验证文件类型(如@castis所说),因为某些用户可能会使用某些扩展名重命名其文件并上传它。

Below is a code sample to validate a text file, you can use similar method to validate image type. 下面是一个验证文本文件的代码示例,您可以使用类似的方法来验证图像类型。

$file_type =  mime_content_type($_FILES['img']['tmp_name']);

if($file_type == 'text/plain'){
    echo "file type is text";
}
?>

<form action="#" method="post" enctype="multipart/form-data">
  <input type="file" name="img">
  <input type="submit" value="Submit">
</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM