【问题标题】:PHP how to limit file type condition like jpg, gif, png?PHP如何限制jpg,gif,png等文件类型条件?
【发布时间】:2014-03-25 11:45:10
【问题描述】:

请问PHP图片上传如何限制文件类型?我想将其限制为仅 png、jpg 和 gif。抱歉这个菜鸟问题。

我尝试的是在条件中添加“或”。但是为什么当我上传 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;
} 

?> 

【问题讨论】:

  • 如果文件类型是您想要的文件类型之一,为什么它会起作用?
  • @Anthony,我只想允许 png、jpg 和 gif。如果文件不是其中之一,则 echo "You may only upload, png, jpg or gif.
  • 您需要将 Or 更改为 And,因为您正在检查所有三个是否 not 为真,因此所有三个都必须通过。所以改变||到&&

标签: php


【解决方案1】:

您可以使用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;
}

【讨论】:

  • @user2192094 - 很高兴为您提供帮助 :) 编码愉快!
【解决方案2】:

这样做

$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
{....
}

【讨论】:

  • 这是一个外部库,答案错误地假设每个人都熟悉。
猜你喜欢
  • 2012-12-21
  • 1970-01-01
  • 2014-01-10
  • 1970-01-01
  • 1970-01-01
  • 2020-09-01
  • 2013-04-25
  • 2013-05-10
  • 2011-05-25
相关资源
最近更新 更多