LiveEn
LiveEn

Reputation: 3253

Set default image if no image is selected to upload in codeigniter

I'm doing a script that will upload an image and save the image path in the database. The only problem that I have is if a user doesn't upload an image I want to set a default image.

But in codeigniter when an image is not selected it automatically gives an error saying that the input file hasn't been selected.

my controller

  if ( !$this->upload->do_upload('image'))
     {
    $error = array('error' => $this->upload->display_errors());
    $this->load->view('upload_success', $error);

     }
    else {
        $image_data=array('image_info' => $this->upload->data('image')); 
        $image_path=$image_data['image_info']['full_path'];

        $data =array(
        'submitedby'=>$username,
        'city'=>$this->input->post('towncity'),
        'image' => $image_path

);  
   }

Can someone please suggest me how to set a default image if the user hasn't selected an image without displaying the default error?

Upvotes: 3

Views: 7389

Answers (2)

Chris Schmitz
Chris Schmitz

Reputation: 8247

You could just not make the image field required and then you can set a default image in your view if there is no image found. That way you don't have all kinds of duplicate images being uploaded and you'll be able to update your default image for everyone easily whenever you want.

Upvotes: 1

birderic
birderic

Reputation: 3765

In the clause where do_upload() fails, check to see if the file was uploaded.

if (!$this->upload->do_upload('image')) {

    if (!empty($_FILES['image']['name'])) {
        // Name isn't empty so a file must have been selected
        $error = array('error' => $this->upload->display_errors());
        $this->load->view('upload_success', $error);
    } else {
        // No file selected - set default image
        $data = array(
            'submitedby' => $username,
            'city'       => $this->input->post('towncity'),
            'image'      => 'path/to/default/image',
        );
    }

} else {
    $image_data = array('image_info' => $this->upload->data('image'));
    $image_path = $image_data['image_info']['full_path'];

    $data = array(
        'submitedby' => $username,
        'city'       => $this->input->post('towncity'),
        'image'      => $image_path,
    );
}

This could be refactored further but the point is that you can check $_FILES['field_name']['name'] to see if a file was selected.

Upvotes: 3

Related Questions