PHP上传图片->无效的文件 [英] PHP upload image -> Invalid file

查看:90
本文介绍了PHP上传图片->无效的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用lampp的archlinux上(最新版本) 我从w3c-school学习php, 我在页面上上传文件,在这里我的脚本什么也不能上传 唯一让我返回的是曾经的无效文件(.jpg .png ecc ..) 这是代码:

i'm on archlinux with lampp(last version) i learn php from w3c-school, i'm on page upload file and here my script can't upload nothing the only thing return me is Invalid File ever (.jpg .png ecc..) here is the code:

 <?php


include "config_db.php";

$name = "/upload/" . $_FILES['file']['name'];
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = in_array(explode(".", $_FILES["file"]["name"]), $allowedExts);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 100000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      echo '<img src="upload/' . $_FILES["file"]["name"] . '">';
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

推荐答案

您正在以错误的方式检查扩展名.这应该是这样的:

Your are checking extension in incorrect way. Here is how it should be:

$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
header ("Content-Type: text/plain");
if ((($_FILES["file"]["type"] == "image/gif")
  || ($_FILES["file"]["type"] == "image/jpeg")
  || ($_FILES["file"]["type"] == "image/png")
  || ($_FILES["file"]["type"] == "image/pjpeg"))
  && ($_FILES["file"]["size"] < 100000)
  && in_array ($extension, $allowedExts)) echo "Success";
else echo "Error";

此代码对我来说可以正常工作,并具有以下形式:

This code works fine for me together with the following form:

<form method="POST" enctype="multipart/form-data" action="upload.php">
  <input type="file" name="file" />
  <input type="submit" />
</form>

这篇关于PHP上传图片-&gt;无效的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆