如果输入文件为空 php,如何设置默认 none.png 图像

how to set default none.png image if input file empty php

如果输入文件为空并且我使用这样的语句,我尝试应用 none.PNG。我需要修复它才能在我的系统中使用它。谢谢你。

if(empty($image)){
 $name = md5(time() . rand(0, 999)) . '.jpeg';
}else{
 $name = 'none.jpeg';
}

public function saveimage()
{
    if (isset($_POST['image_loc'])) {
        $image = $_FILES['image_loc'];
        $allowed = array('image/jpeg', 'image/jpg', 'image/png');
         // print_r($image);
         // die();

         // check for erros
        if ($image['error'] != 0) {
            die('File upload error: ' . $image['error']);
        }

         // check if is image
        if (in_array($image['type'], $allowed)) {

            $name = md5(time() . rand(0, 999)) . '.jpeg';
            move_uploaded_file($image['tmp_name'], ROOT . '/public/img/pics/' . $name);


            echo $image['tmp_name'];
            $this->insert($name);

        }
    }
}

修改代码后 结果仅在我上传文件时显示。如果不上传文件,我还需要 none.PNG 来显示。我怎样才能做到这一点。

public function saveimage()
{
    if (isset($_POST['image_loc'])) {
        $image = $_FILES['image_loc'];


        $allowed = array('image/jpeg', 'image/jpg', 'image/png');
             // print_r($image);
             // die();


             // check if is image
        if (in_array($image['type'], $allowed)) {


            ////////////////////////// here ///////////////////////
            if (empty($image)) {
                $name = md5(time() . rand(0, 999)) . '.jpeg';
            } else {
                $name = 'none.jpeg';
            }
            ////////////////////////// here ///////////////////////

            move_uploaded_file($image['tmp_name'], ROOT . '/public/img/pics/' . $name);

            echo $image['tmp_name'];
            $this->insert($name);

        }
    }
}

如果 $_POST["image_loc"] 是远程 url,您可以使用小于 returns 文件大小的函数。所以可以检查它是否 returns 0 或不。如果 $_POST["image_loc"] 不是远程 url 并且它是您服务器中的图像路径,您可以简单地使用 filesize($image_path) 函数来获取图像大小。

function get_image_size($image_url){
 $ch = curl_init($image_url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
 curl_setopt($ch, CURLOPT_HEADER, TRUE);
 curl_setopt($ch, CURLOPT_NOBODY, TRUE);
 $data = curl_exec($ch);
 $size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
 curl_close($ch);
 return $size;
}