You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CodeIgniter中实现用户头像管理及现有图片显示功能?

Hey there! Let's walk through adding the avatar functionality you need for your CodeIgniter script. I've put together a step-by-step solution that covers upload, display, re-upload, and delete—let's dive in:

Step 1: Update Your User Database Table

First, you'll need to add a column to your users table to store the avatar file path. Run this SQL query (adjust the table name if yours is different):

ALTER TABLE `users` ADD `avatar` VARCHAR(255) DEFAULT NULL;
Step 2: Create/Update the User Model

Add these methods to your existing user model (or create a dedicated avatar model if you prefer):

class User_model extends CI_Model {
    // Update user's avatar path in database
    public function update_avatar($user_id, $avatar_path) {
        $this->db->where('id', $user_id);
        return $this->db->update('users', ['avatar' => $avatar_path]);
    }

    // Fetch user's avatar path
    public function get_user_avatar($user_id) {
        $query = $this->db->select('avatar')->where('id', $user_id)->get('users');
        return $query->row() ? $query->row()->avatar : NULL;
    }

    // Delete avatar (remove file + clear database record)
    public function delete_avatar($user_id) {
        $avatar_path = $this->get_user_avatar($user_id);
        if ($avatar_path && file_exists(FCPATH . $avatar_path)) {
            unlink(FCPATH . $avatar_path);
        }
        $this->db->where('id', $user_id);
        return $this->db->update('users', ['avatar' => NULL]);
    }
}
Step 3: Build the Avatar Controller

Create a new controller to handle upload and delete actions:

class Avatar extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->model('user_model');
        $this->load->library('upload');
        $this->load->library('session');

        // Redirect to login if user isn't authenticated
        if (!$this->session->userdata('user_id')) {
            redirect('login');
        }
    }

    // Handle avatar upload/re-upload
    public function upload() {
        // Configure upload settings
        $config = [
            'upload_path'   => './uploads/avatars/',
            'allowed_types' => 'gif|jpg|png|jpeg',
            'max_size'      => 2048, // 2MB limit
            'file_name'     => 'avatar_' . $this->session->userdata('user_id') . '_' . time(),
            'overwrite'     => TRUE, // Override old avatar on re-upload
        ];

        $this->upload->initialize($config);

        if (!$this->upload->do_upload('avatar')) {
            // Upload failed: send error message to profile page
            $this->session->set_flashdata('avatar_error', $this->upload->display_errors());
            redirect('profile');
        } else {
            // Upload succeeded: get file data
            $upload_data = $this->upload->data();
            $new_avatar_path = 'uploads/avatars/' . $upload_data['file_name'];

            // Delete old avatar (if exists)
            $old_avatar = $this->user_model->get_user_avatar($this->session->userdata('user_id'));
            if ($old_avatar && file_exists(FCPATH . $old_avatar)) {
                unlink(FCPATH . $old_avatar);
            }

            // Update database with new avatar path
            $this->user_model->update_avatar($this->session->userdata('user_id'), $new_avatar_path);
            $this->session->set_flashdata('avatar_success', 'Avatar updated successfully!');
            redirect('profile');
        }
    }

    // Handle avatar deletion
    public function delete() {
        $this->user_model->delete_avatar($this->session->userdata('user_id'));
        $this->session->set_flashdata('avatar_success', 'Avatar deleted successfully!');
        redirect('profile');
    }
}

Don't forget to create the uploads/avatars/ directory in your project root and set its permissions to 755 or 777 so the server can write to it.

Step 4: Update the Profile View

Modify your profile page to display the avatar and add upload/delete controls:

<div class="profile-avatar-container">
    <?php 
    $user_avatar = $this->user_model->get_user_avatar($this->session->userdata('user_id'));
    // Show user's avatar or default if none exists
    if ($user_avatar): ?>
        <img src="<?php echo base_url($user_avatar); ?>" alt="Your Avatar" class="profile-avatar" width="180" height="180">
    <?php else: ?>
        <img src="<?php echo base_url('assets/images/default-avatar.png'); ?>" alt="Default Avatar" class="profile-avatar" width="180" height="180">
    <?php endif; ?>
</div>

<!-- Avatar Upload Form -->
<div class="avatar-management">
    <?php if ($this->session->flashdata('avatar_error')): ?>
        <div class="alert alert-danger"><?php echo $this->session->flashdata('avatar_error'); ?></div>
    <?php endif; ?>
    <?php if ($this->session->flashdata('avatar_success')): ?>
        <div class="alert alert-success"><?php echo $this->session->flashdata('avatar_success'); ?></div>
    <?php endif; ?>

    <?php echo form_open_multipart('avatar/upload'); ?>
        <label for="avatar">Upload/Update Avatar:</label>
        <input type="file" id="avatar" name="avatar" accept="image/*" required>
        <button type="submit" class="btn btn-primary">Save Avatar</button>
    <?php echo form_close(); ?>

    <?php if ($user_avatar): ?>
        <?php echo form_open('avatar/delete'); ?>
            <button type="submit" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete your avatar?')">Delete Avatar</button>
        <?php echo form_close(); ?>
    <?php endif; ?>
</div>
Step 5: Add Routes

Add these lines to application/config/routes.php to map the controller actions:

$route['avatar/upload'] = 'avatar/upload';
$route['avatar/delete'] = 'avatar/delete';

This setup will handle all your required features: users can upload avatars, see them on their profile, re-upload to replace old ones, and delete avatars entirely. Make sure to adjust paths (like the default avatar location) to match your project's structure.

内容的提问来源于stack exchange,提问作者dbusybrainsHub

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:19:50