php - 在 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]);
}
请帮助我如何为每个特定用户上传和存储照片。
解决方案
因此,要上传照片,您至少需要三件事:
- 可以选择和提交文件的表格
- 可以处理此类请求并将文件保存在服务器上的控制器
- 您保存上传文件的名称(或完整路径)的数据库字段,以便以后显示或删除它
但我也可以为您提供一些代码。
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);
}
您可以配置用于上传文件的文件夹和其他限制。在此示例中,上传文件夹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');
这些基本的东西可以扩展,例如,使用表单验证。
推荐阅读
- java - gRPC 客户端如何知道网络丢失/故障?
- c++ - RValue 引用的大小是多少?
- matlab - 碰撞问题:将圆弧的旋转中心放在一个半圆上并旋转它直到它接触到它所在的半圆
- reactjs - 我们如何在 antd 中根据 jsx 条件和数组索引添加元素
- javascript - 以更短的方式替换下面的 if、else-if、else
- amazon-ecs - 应用程序负载均衡器返回 504Gateway Timeout
- php - 数组没有为 foreach 循环提供正确的输出
- node.js - 除了process.env之外,有没有办法在整个项目中访问节点js中的变量(aws-ssm)?
- flutter - Flutter 项目规模确实很大。如何减少它?
- google-cloud-platform - 当您想继续使用分页检索结果时,在 BigQuery 表中进行分页的最佳方法是什么?