如何在PHP中检查图像文件是否输入?

时间:2016-08-08 09:46:00

标签: php html html5 image

我在edit.PHP中有一个输入字段为

<form  method='POST' action='update.PHP'>
    <input type='file' name="image" id="image">
</form>

现在在update.PHP我想检查图像文件是否存在我如何检查?我写的脚本是这样的:

if(!empty($_FILES['image'])){

    #then execute this code when there is image uploaded
}else{
    #execute this
}

但是这个脚本不起作用......每次添加或不添加图像都会返回true ...如果图像不在那里,我该如何阻止执行代码呢?

这是完整的PHP脚本,如果它可以帮助任何人解决我的问题

if(!empty($_FILES['image'])){
  if(isset($_FILES['image'])){
    $errors= array();
    $file_name = $_FILES['image']['name'];
    $file_size =$_FILES['image']['size'];
    $file_tmp =$_FILES['image']['tmp_name'];
    $file_type=$_FILES['image']['type'];
    $ff_ext = explode('.',$_FILES['image']['name']);
    $file_ext=strtolower(end($ff_ext));

    $expensions= array("jpeg","jpg","png");
    $id=md5(uniqid());

    if(in_array($file_ext,$expensions)=== false){
        $errors[]="extension not allowed, please choose a JPEG or PNG file.";
    }

    if($file_size > 2097152){
        $errors[]='File size must be excately 2 MB';
    }

    if(empty($errors)==true){
        $filename = $id."/".$file_name;
        ////IF DIRECTORY NOT EXISTS CREATE ONE
        if(!file_exists("images/".$id)){
            if(!mkdir("images/".$id,0755,true)){
                    $error = error_get_last();
                        echo $error['message'];
                            echo 'failed';
                }
            }

        $filename = $id."/".$file_name;
        move_uploaded_file($file_tmp,"images/".$filename);
        $dirn = "images/".$filename;
    }else{
        print_r($errors);
    }
}
 }else{
    $dirn = $user['profile_pic']; //link of the existing profile picture       address 
   }

PS:HTML部分没有问题。

2 个答案:

答案 0 :(得分:2)

替换PHP代码的这一部分

instantiate

用这个

if(!empty($_FILES['profile_image'])){

    #then execute this code when there is image uploaded
}else{
    #execute this
}

这部分HTML代码

if (is_uploaded_file($_FILES ['profile_image'] ['tmp_name'])) {
    #then execute this code when there is image uploaded
} else {
    #execute this
}

用这个

<form  method='POST' action='update.PHP'>

答案 1 :(得分:1)

在表格标签中添加

  enctype="multipart/form-data"