PHP如何限制文件类型条件,如jpg,gif,png?

时间:2014-03-25 11:45:10

标签: php

我想问一下如何限制PHP图片上传的文件类型?我想将它限制为png,jpg和gif。对不起这个noob问题。

我试过的是在条件中添加'OR'。但是,当我上传jpg,gif或png时,为什么它不起作用呢?

<?php 

//limit file type condition
if(!($_FILES["photo"]["type"] == "image/png") 
|| !($_FILES["photo"]["type"] == "image/jpg") 
|| !($_FILES["photo"]["type"] == "image/gif")){

echo "You may only upload png, jpg or gif.<br>";
$ok=0;
} 

?> 

2 个答案:

答案 0 :(得分:2)

使用in_array()

,可以缩短范围,提高可读性
$allowed_extensions = array( "image/png", "image/jpg", "image/gif" );

if ( !in_array( $_FILES[ "photo" ][ "type" ], $allowed_extensions ) ){
  echo "You may only upload png, jpg or gif.<br>";
  $ok = 0;
}

答案 1 :(得分:0)

这样做

$config['upload_path'] = '';
$config['allowed_types'] = 'gif|jpg|png';       //pic type
$config['max_size'] = '100';
$config['max_width']  = '1024';
$config['max_height']  = '768';
$this->load->library('upload', $config);
$this->upload->initialize($config);

if ( ! $this->upload->do_upload())
{
   $error = array('error' => $this->upload->display_errors()); //you will get error statement in $error
}
else
{....
}
相关问题