display default image if user have no photo codeig

2019-06-12 16:02发布

问题:

In displaying my image getting it from the database is fine but I want to display the default image if no user hasn't uploaded a photo yet. I saved a no-avatar.jpg to my /uploads folder



Here is my display user image.

view

<img height="180px" width="180px"class="ppborder" src="<?php echo base_url().'/uploads/'.$this->session->userdata('image'); ?>"> 

upload

public function updatephoto($id)
    {
    if ((int)$id < 1)//$id is not an integer
    {
    redirect('Memberlogincontroller/member_view', 'refresh');
    }
    else{
    $this->load->helper(array('form','file','url'));
    $this->load->library('form_validation');
    $config_image = array(
        'upload_path'   => './uploads/',
        'allowed_types' => 'gif|jpg|png',
        'max_size'      => '1024',
        'overwrite'     => true

    );
    $this->load->library('upload', $config_image);

    if($this->form_validation->run()==false and empty($_FILES['userfile']['name'][0]))
        {
            $id = $this->session->userdata('id');
            $memberinfo = array(
                'error_image' => ''
            );
        $this->session->set_flashdata('flashError', 'Oops no photo selected', $memberinfo);         
        redirect('index.php/Memberlogincontroller/editphoto/'.$id, 'refresh');
        }       
    else
        {           
            $this->upload->do_upload();
             $data = array('upload_data' => $this->upload->data());
             $this->image_resize($data['upload_data']['full_path'], $data['upload_data']['file_name']);
             $id = $this->session->userdata('id');
             $this->db->where('id', $id);
             $query = $this->db->get('member'); 
            $data = array(
                'image' => $data['upload_data']['file_name']    
        );
        $this->db->update('member',$data,array('id'=>$id));          
        $this->session->set_userdata($data); 
        $this->session->set_flashdata('flashSuccess', 'Your photo has been updated.');
        redirect('index.php/Memberlogincontroller/getMember/'.$id, 'refresh');       
    }       
    }
    }

How to display my default image?

回答1:

Just add a condition to check if image is available. If yes show user's image else default image.

<?php
$user_img = !empty($this->session->userdata('image')) ? $this->session->userdata('image') : 'no-avatar.jpg';
?>
<img height="180px" width="180px" class="ppborder" src="<?php echo base_url().'/uploads/'.$user_img; ?>">