【问题标题】:how to set default none.png image if input file empty php如果输入文件为空 php,如何设置默认的 none.png 图像
【发布时间】:2018-10-21 08:51:11
【问题描述】:

如果输入文件为空并且我使用这样的语句,我尝试应用 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);

        }
    }
}

【问题讨论】:

  • 现在有什么问题?你在哪里使用第一个 sn-p?
  • @jeff none.png 如果输入文件为空,则不显示。我在 //////////////////////////////////////////////////////////////////////////////////////////////// ////////

标签: php file-upload upload defaultifempty


【解决方案1】:

如果$_POST["image_loc"] 是远程URL,您可以使用下面的函数返回文件大小。所以可以检查它是否返回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;
}

【讨论】:

    猜你喜欢
    • 2013-09-03
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多