简体   繁体   中英

Check if file field is set codeigniter

Situation: got a news feed like system where you can add an image per post. These posts can also be updated. When there is an update the image value in database should remain the same unless the image gets changed.

Currently using this in my controller:

            $this->load->library('upload'); //initialize
            if (isset($_FILES['userfile']) && is_uploaded_file($_FILES['userfile']['tmp_name'])) {
                $this->upload->initialize($config);
                $this->upload->do_upload('userfile');
                $imageData = $this->upload->data();
                $data['front_image'] = $imageData['file_name'];
             }

But as you can gues this doesn't work out. Any suggestions?

            $this->load->library('upload'); //initialize
        if ($_FILES['userfile'][size] !=0 && is_uploaded_file($_FILES['userfile']['tmp_name'])) {
            $this->upload->initialize($config);
            $this->upload->do_upload('userfile');
            $imageData = $this->upload->data();
            $data['front_image'] = $imageData['file_name'];
         }

cheking aagainst the file size solved the issue.

You may be doing more work that you need to. I haven't used CI in a while, but I'm pretty sure that you can just check the result of $this->upload->do_upload() . I believe the Upload class will check for the file existence for you and will return a falsey (<- not a word) value.

$this->load->library('upload', $config);
// or $this->upload->initialize($config);// if you're autoloading

if ($this->upload->do_upload()) {
    $imageData = $this->upload->data();
    $data['front_image'] = $imageData['file_name'];
} else {
    echo $this->upload->display_errors();
}

Also, if you're in a framework (CodeIgniter, Laravel, etc), you really shouldn't have to check the global PHP vars. Most of that stuff is wrapped for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM