【问题标题】:check if $_FILES is empty or not, file size, file exists检查 $_FILES 是否为空,文件大小,文件是否存在
【发布时间】:2017-05-11 01:57:34
【问题描述】:

我有一个编辑表单,用户可以编辑他/她的信息。 它包含名字、姓氏、用户名、类别(从类别表中选择数据)和图像输入。我想要一个可以检查图像类型、大小、是否为空的功能。实际上,如果用户没有上传照片,则不需要检查它,但如果用户上传照片,则该函数会检查其文件类型(jpg,png,jpeg),并检查文件大小是否大于1MB。

实际上,当所有输入都填写完毕并上传图片时,我的代码才有效。但是如果用户没有上传照片,则会出现此消息。它是更新表单,所以也许用户之前上传了一张照片,他/她不想更改那张照片。所以我的问题是用户在上传图片之前无法提交他/她的信息。

if (isset($_POST['submit']))
{
$Title = test_input($_POST['Title']);
$Category = $_POST['Category'];
$Content = test_input($_POST['Post']);
$Author = test_input($_POST['Author']);
$ref = test_input($_POST['reference']);

$image= $_FILES["img"]["name"];
$imgSize = $_FILES["img"]["size"];
$image_tmp= $_FILES["img"]["tmp_name"];

$traget_dir = "../files/img/content/";
$target_file = $target_dir.basename($_FILES["img"]["name"]);
$ImageFileType=pathinfo($target_file,PATHINFO_EXTENSION);



if(empty($Title))
{
    $msg=" * title couldn't be empty";
}
else if(empty($Content))
{
    $msg=" * Content couldn't be empty";
}
else if(empty($Author))
{
    $msg=" * Author couldn't be empty";
}
else if($image =="")
{
    echo $msg=" * you must choose a photo";
    $uploadOK=1;
}

else if($ImageFileType !="jpg" && $ImgeFileType != "gif" &&$ImageFileType     !="png" )
{
    echo $msg=" * only JPG, PNG, GIF are allowed";
}

else if($imgSize > 1024000)
{
    echo $msg= " * the photo shouldn't be greater that 1MB";
}



else if(move_uploaded_file($_FILES["img"]["tmp_name"],$target_file))
{


     echo $msg1= " * the file ".basename($_FILES['img']['name'])." has been  uploaded";


    $uploadOk = 0;
}

$query= "UPDATE content SET (`Title`='$Title' ,`Text`= '$Content'  ,`Writer`='$Author',`Reference`='$ref',`Image`= '$image')  where Content_ID='$id' ";

 if(mysqli_query($_SESSION['con'],$query))
{
        $msg1="post published";

}
else
    {
        echo $msg="there was an error occured      <br>".mysqli_error($_SESSION['con']);
    }here

【问题讨论】:

  • 首先,使用is_uploaded_file()函数检查用户是否上传了任何图片,然后相应地处理您的表单。
  • 你必须告诉我们什么不起作用,把它编辑到你的帖子中。

标签: php


【解决方案1】:

您可以通过以下方式获取文件大小(以字节为单位):

$_FILES['img']['size']

要检查它是否是图像文件或图像文件格式,您可以通过getimagesize() 像这样检查$_FILES['img']['tmp_name']php how to use getimagesize() to check image type on upload

要检查文件是否上传,您可以使用error 进行检查。错误号 4 表示文件未上传:

if ($_FILES['img']['error']==4){
    echo 'Not uploaded';
}

在这里你可以看到更多关于Error Messages Number的信息

【讨论】:

  • 我想如果文件未上传不显示任何消息,只需继续其他代码或提交表单。并在用户上传文件时检查文件的大小、类型
猜你喜欢
  • 2013-03-31
  • 1970-01-01
  • 1970-01-01
  • 2019-04-24
  • 2011-05-03
  • 1970-01-01
  • 2021-12-25
相关资源
最近更新 更多