我正在创建一个上传系统,每当用户上传图像扩展名以外的文件类型(例如jpg / jpeg / gif)时,脚本就会中断。在我重新启动phpstorm
之前,PHP不会加载,而且我的代码非常小。我不希望用户上传.exe或任何其他文件扩展名。
这是我的代码:
if (!$_FILES['file']['tmp_name'])
{
$uploaderrors[] = "Please choose image";
}
$check = getimagesize($_FILES['file']['tmp_name']);
if($check == false)
{
$uploaderrors[] = "Please choose image";
}
}
脚本中断,破坏了UX。无论如何我能解决这个问题吗?
答案 0 :(得分:0)
只需使用Javascript(可能是JQuery)来检查用户在PHP启动之前上传正确的文件格式......这将是在客户端执行此操作的一种方式。这是一个例子:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
(function($) {
$(document).ready(function(){
// ASSUMING THAT YOUR FILE INPUT HAS A CLASS-NAME OF "file_upload"
// WE CAN SIMPLY GRAB IT INTO A VARIABLE LIKE SO:
var pixFile = $(".file_upload");
// NOW, WHEN THE USER INTERACTS WITH THIS FILE-INPUT
// WE CAN REACT TO THE CHANGE EVENT...
pixFile.on("change", function(evt){
var dis_val = $(this).val();
// IF USER TRIES TO UPLOAD ANYTHING OUTSIDE ACCEPTABLE/VALID IMAGE FORMATS
// WE INFORM HIM OF OUR PREFERENCES: HERE WE ARE USING ALERT...
if( !/(\.)(jpg|jpeg|png|gif|bmp)$/.test(dis_val) ){ // ADD OTHER FORMATS YOU WISH TO SUPPORT: 'tiff, psd, pdf'
alert("You can only upload image Files (JPG, JPEG, PNG, GIF, BMP)"); // ADD OTHER FORMATS YOU WISH TO SUPPORT
// THEN IMMEDIATELY RESET THE VALUE OF THE UPLOADED FILE TO NULL
$(this).val(null);
return false;
}else{
// OTHERWISE: WE KNOW THAT USER UPLOADED THE ACCEPTABLE FILE FORMAT(S)
// YOU MAY OR MAY NOT WANT TO REACT TO THIS... THE CHOICE IS YOURS
// AND YOU MAY AS WELL JUST DELETE THE ENTIRE ELSE CLAUSE (IF YOU SO WISH)
}
});
});
})(jQuery);
</script>