Search code examples
phpfile-uploaduploaddefaultifempty

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


I tried to apply none.PNG if input file empty and i use statement like this. I need to fix this to use it in my systems. thank you.

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);

        }
    }
}

After edited the code The result show only if I upload file. i need none.PNG as well to show if not upload file. how can i do this.

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);

        }
    }
}

Solution

  • If $_POST["image_loc"] is remote url, you can use function below that returns file size. So can check if it returns 0 or not. If $_POST["image_loc"] isn't remote url and it's image path in your server, you can simply use filesize($image_path) function to get image size.

    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;
    }