在php Codeigniter中上传用户个人资料图片

时间:2020-09-02 09:20:56

标签: php codeigniter

如何根据user_id上传用户个人资料图片?我正在尝试使每个特定用户都可以在其个人资料上上传照片并存储在数据库中。我不知道如何执行此要求,因此在这里提供了我的代码,如果您能帮助我如何进行操作,将不胜感激。 这是我的profile.php视图

<div class="profile-img">
                <?php if (!empty($user->photo)): ?>
               <img src="/uploads/<?php echo $user->photo; ?>" alt="<?php echo $user->photo; ?>">
                  <?php endif;?>
                  <!-- <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS52y5aInsxSm31CvHOFHWujqUx_wWTS9iM6s7BAm21oEN_RiGoog" alt=""/> -->
                  
                  <?php echo form_open_multipart('users'); ?>
                   <input type="hidden" name="user_id" value="<?php echo $user->id; ?>" />
                 <div class="file btn btn-lg btn-primary">
                     <i class="fa fa-pencil-square-o"></i>
                      <input type="file" name="file" />
                      <input type="submit"  name="submit" value="Upload photo" />
                </form>
                
                </div>
            </div>

这是我的Profile.php控制器,在那里我可以获得个人资料视图所需的所有详细信息。

    function index()
{

     $user_id =  $this->session->userdata('admin');
    if(empty($user_id)){
         redirect('admin/login');
     }
    
   $data['userInfo'] = $this->profile_model->myProfile($user_id);
    
     if($user_id == 3){ // admin
        $data['project12'] = $getAllProjects = $this->profile_model->getAdminProjects();

        //echo '<pre>';
        //print_r($getAllProjects);
        //die;
        $new_array = array();
        foreach($getAllProjects as $key => $row) {
            $new_array[$key]['id'] = $row->id; 
            $new_array[$key]['delete_flag'] = $row->delete_flag; 
            $new_array[$key]['project_name'] = $row->project_name; 
            $new_array[$key]['client_name'] = $row->client_name; 
            $new_array[$key]['company'] = $row->company; 
            $new_array[$key]['project_manager'] = $row->project_manager; 
            $sec_array = explode(",",$row->support_staff);
            if(is_array($sec_array) ){
                foreach($sec_array as $row1){
                    $new_array[$key]['support_staff'][] = $this->profile_model->getUsernameByID($row1);

                }
            }
        }
        
        //print_r($new_array);die;
        $data['project'] = $new_array;

        $data['task_list'] = $this->task_model->getAllTasks();

        $data['incident_list'] = $this->incidents_model->getAllIncidents();


//      echo "<pre>";
// print_r($data['incident_list']);
//      die;

     }else{ // others
         $data['project'] = $this->profile_model->getById_myProjects($user_id);
         $data['task_list'] = $this->task_model->getTaskByUserID($user_id);
         $data['incident_list'] = $this->incidents_model->getIncidentByUserID($user_id);

     }
    if ($this->input->server('REQUEST_METHOD') == 'POST') 
    {
    $this->upload_photo();
    }else{
    $this->load->view('users', [
    //'errors' => $this->upload_errors,
    'users'  => $this->profile_model->get_all()]);
    }



     $this->load->view('admin/profile/index',$data);
}


     $this->load->view('admin/profile/index',$data);
}
private function upload_photo()
    {
    $user_id = $this->input->post('user_id');
    $existing_photo = $this->profile_model->get_photo($user_id)->photo;
    if ($existing_photo && file_exists("./uploads/{$existing_photo}")) {
        unlink("./uploads/{$existing_photo}");
    }
    if (!$this->upload->do_upload('photo')) {
        $this->upload_errors = $this->upload->display_errors();
    }
    $photo = $this->upload->data()['file_name'];
    $this->profile_model->update_photo($user_id, $photo);
   }

这是我的profile_model

function get_all($user_id)
 {
     $query = $this->db->query("SELECT * FROM profile_details where user_id =$user_id");
      return $query->result();

 }


 function get_photo()
{
$query = $this->db->query("SELECT photo FROM profile_details where user_id= $user_id");

}


function update_photo($user_id, $photo)
{
    $this->db->update('profile_details', ['photo' => $photo], ['user_id' => $user_id]);
}

Here is profile_details table

And here is the frontend view

enter image description here

请帮助我如何为每个特定用户上传和存储照片。

1 个答案:

答案 0 :(得分:0)

因此,要上传照片,至少需要三件事:

  • 可以选择并提交文件的表单
  • 可以处理此类请求并将文件保存在服务器上的控制器
  • 您在其中保存上载文件的名称(或完整路径)的数据库字段,以便以后可以显示或删除它

简而言之,我建议您遵循有关creating new itemsuploading files的文档。

但是我也可以为您提供一些代码。

1。假设我们有这样一种上传文件的表格:

<!-- in such a way you can show already uploaded photo -->
<?php if (!empty($user->photo)): ?>
    <img src="/uploads/<?php echo $user->photo; ?>" alt="<?php echo $user->photo; ?>" width="50">
<?php endif;?>

<!-- pay attention to the hidden field that contains user_id that will be needed during saving the file 
and also to the "multipart" attribute that is required for uploading files.
CodeIgniter automatically can add these attributes using form_open_multipart function -->
<?php echo form_open_multipart('users'); ?>
    <input type="hidden" name="user_id" value="<?php echo $user->id; ?>" />
        <input type="file" name="photo" />
        <input type="submit" name="submit" value="Upload photo" />
</form>

2。然后您应该准备好控制器以接收这些数据。在我的示例中,这是一个具有Users方法的index控制器:

/**
 * Index Page for Users controller.
 * It shows a list of existing users for GET method and tries to save user's photo for POST
 */
public function index()
{
    // if we send a form on these method then try to save uploaded file
    if ($this->input->server('REQUEST_METHOD') == 'POST') {
        $this->upload_photo();
    }

    // otherwise, show list of existing users and possible uploading errors
    $this->load->view('users', [
        'errors' => $this->upload_errors,
        'users'  => $this->user_model->get_all()]);
}

/**
 * Method for saving user's profile photo
 */
private function upload_photo()
{
    // get user id from hidden form field
    $user_id = $this->input->post('user_id');

    // delete existing file if it exists
    $existing_photo = $this->user_model->get_photo($user_id)->photo;
    if ($existing_photo && file_exists("./uploads/{$existing_photo}")) {
        unlink("./uploads/{$existing_photo}");
    }

    // "photo" is the name of input element in uploading form
    if (!$this->upload->do_upload('photo')) {
        // save uploading errors to show them on the page
        $this->upload_errors = $this->upload->display_errors();
    }

    // get file name from uploaded data
    $photo = $this->upload->data()['file_name'];

    // save uploaded file name to database for current user
    $this->user_model->update_photo($user_id, $photo);
}

您可以configure文件夹来上传文件和其他限制。在此示例中,上传文件夹位于项目根目录中的uploads

3。在数据库模型中,您仅需要两种简单的方法来获取和更新photo表中的users字段:

/**
 * Class User_model
 */
class User_model extends CI_Model
{
    private $table_name = 'users';

    /**
     * @return mixed
     */
     public function get_all()
     {
         return $this->db->get($this->table_name)->result();
     }

    /**
     * Get filename of user's profile photo
     *
     * @param $user_id
     *
     * @return mixed
     */
    public function get_photo($user_id)
    {
        $this->db->select('photo');

        return $this->db->get_where($this->table_name, ['id' => $user_id])->row();
    }

    /**
    * Update "photo" field for "Users" database table
    *
    * @param $user_id
    * @param $photo
    */
    public function update_photo($user_id, $photo)
    {
        $this->db->update($this->table_name, ['photo' => $photo], ['id' => $user_id]);
    }
}

对于这些操作,需要加载几个库和助手。您可以在application/config/autoload.php中完成该操作:

$autoload['libraries'] = array('database', 'upload');
$autoload['helper'] = array('form', 'file');

例如,可以使用form validation扩展这些基本内容。

相关问题