zec*_*ude 11 php upload file-type
我正在创建一个用户上传文件的页面.如果文件类型是jpg,gif和pdf,我想要if语句来创建$ error变量.
这是我的代码:
$file_type = $_FILES['foreign_character_upload']['type']; //returns the mimetype
if(/*$file_type is anything other than jpg, gif, or pdf*/) {
$error_message = 'Only jpg, gif, and pdf files are allowed.';
$error = 'yes';
}
Run Code Online (Sandbox Code Playgroud)
我在构造if语句时遇到了困难.我怎么说呢?
ani*_*son 21
将允许的类型放在数组中并使用in_array().
$file_type = $_FILES['foreign_character_upload']['type']; //returns the mimetype
$allowed = array("image/jpeg", "image/gif", "application/pdf");
if(!in_array($file_type, $allowed)) {
$error_message = 'Only jpg, gif, and pdf files are allowed.';
$error = 'yes';
}
Run Code Online (Sandbox Code Playgroud)
我刚才意识到你也想要允许PDF文件.在这种情况下,请查看PHP的Fileinfo类和函数.但就安全性而言,你仍然不应该依赖$_FILES[]['type']:)
我将其余的留在这里,以防其他人发现这个问题
要检查图像的mime类型,$_FILES[]['type']可能不安全.此数据由浏览器发送,可能很容易被欺骗.
getimagesize()如果您只想允许上传图像(尽管它可能具有误导性的名称),您应该使用该功能.此功能不仅可以为您提供尺寸,还可以提供您可能需要的有关图像的所有数据.
我在图像处理类中使用了以下脚本:
private function load_image_data($image_file) {
// Firstly, to disambiguate a loading error with a nonexistant file error,
// check to see if the file actually exists.
if( ! file_exists($image_file) ) {
throw new Nonexistent_Image_Exception("The file '{$image_file}' does not exist");
}
// We're going to check the return value of getimagesize, so we don't
// need any pesky warnings or notices popping up, since we're going to
// stop execution of this function if something goes wrong.
$image_data = @getimagesize($image_file);
if( $image_data === false ) {
throw new Load_Image_Exception("Could not get image data from '{$image_file}'");
}
$this->size = new Dimensions($image_data[0], $image_data[1]);
$this->mime = $image_data['mime'];
}
Run Code Online (Sandbox Code Playgroud)
请注意,getimagesize()返回包含'mime'索引的关联数组.这里的数据是可靠的.
在另一个函数中,我检查了图像的mime类型,并使用适当的GD函数将其转换为PNG:
private function load_image($image_file) {
// Suppress warning messages because we're going to throw an
// exception if it didn't work instead.
switch( $this->mime ) {
case 'image/jpeg':
case 'image/pjpeg':
$this->image = @imagecreatefromjpeg($image_file);
break;
case 'image/gif':
$this->image = @imagecreatefromgif($image_file);
break;
case 'image/png':
$this->image = @imagecreatefrompng($image_file);
break;
default:
throw new Invalid_Image_Exception("The image was of an invalid type");
}
if( $this->image === false ) {
throw new Load_Image_Exception("Loading of image '{$image_file}' failed");
}
}
Run Code Online (Sandbox Code Playgroud)
您可能不需要执行所有这些操作,但是您可以看到为指定的文件类型显示的mime类型.请注意,jpeg可能有两种不同的mime类型.
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
35336 次 |
| 最近记录: |