【问题标题】:PHP Upload Image formats only? [duplicate]PHP 只上传图片格式? [复制]
【发布时间】:2014-03-02 14:57:45
【问题描述】:

我有一个上传系统,它将上传文件然后记录在我的数据库中。无论如何它都可以正常工作,但我怎样才能让它只上传图像而不上传其他任何东西?

我的代码:

if($_POST[add]){



$dataType = $_POST["dataType"];
$title = $_POST["title"];
$fileData = pathinfo(basename($_FILES["image"]["name"]));
$fileName = uniqid() . '.' . $fileData['extension'];
$target_path = ("userfiles/profilepic/" . $fileName);

while(file_exists($target_path))
{
    $fileName = uniqid() . '.' . $fileData['extension'];
    $target_path = ("userfiles/profilepic/" . $fileName);
}

if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_path))
{

  $sql = $dbh->prepare("UPDATE users SET `profilepic` = 'userfiles/profilepic/$fileName' WHERE `id` = '".$member["id"]."'");

    $sql->execute();
    $retval = $sql->fetch(PDO::FETCH_ASSOC);

    echo "Your profile picture has successfully been updated";


}
else
{
    echo "oh noes.. there was an error :( Please do try again!";
}

}

【问题讨论】:

  • 在 Google 上花几分钟会得到很多结果。
  • @Fred-ii- 抱歉,我应该提到我已经对此进行了研究。我尝试了很多不同的东西,但似乎没有一个对我有用。我最接近的应该是上传一个 .png 并提出这不是图像文件。但这只是停止.. 上传不同的格式,.png、.gif 格式的文件呢?
  • 查看此w3schools.com/php/php_file_upload.asp 下的“上传限制”代码可用
  • @Mobi 我检查了,但不知道如何将它集成到我的代码中。
  • See this answer 在 SO。 @user3370962 - 在谷歌搜索关键字“只允许图片上传 php”和 this one 后找到

标签: php upload format restrict


【解决方案1】:

基于this answer

if($_POST[add]){

$file_type = $_FILES['image']['type']; //returns the mimetype

$allowed = array("image/jpeg", "image/gif", "image/png");
if(!in_array($file_type, $allowed)) {
  $error_message = 'Only jpg, gif, and png files are allowed.';

  echo $error_message;

  exit();

}

$dataType = $_POST["dataType"];

... rest of your code below

脚注:

【讨论】:

  • 谢谢!效果很好。
  • 好,很高兴听到这个消息,不客气。 @user3370962
  • 如果答案已经存在,那么这个问题应该已经被标记为重复了。
  • OP 不知道如何实现它。请阅读 OP 问题下的 cmets。 @Joraid - 向某人伸出援助之手是 SO 的一部分。
  • 是的,看来问题不在于找到方法,而在于整合它。
猜你喜欢
  • 1970-01-01
  • 2019-05-06
  • 1970-01-01
  • 2013-03-08
  • 2015-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-16
相关资源
最近更新 更多