Home > PHP Framework > ThinkPHP > How to modify user avatar in ThinkPHP framework

How to modify user avatar in ThinkPHP framework

PHPz
Release: 2023-04-10 09:26:42
Original
832 people have browsed it

ThinkPHP is a very popular PHP framework in the domestic market. Many developers and companies are using it to develop various web applications. Among them, user avatar is one of the most common functions in web applications. Therefore, this article will introduce how to implement the function of modifying user avatar in the ThinkPHP framework.

1. Requirements Analysis

Before starting to write code, we first need to clarify the requirements, including:

1. Users can upload avatars when registering and save the avatars to Local server;

2. After logging in, users can modify their avatar and save the modified avatar to the local server.

In response to the above requirements, the following will be explained in detail in two parts.

2. Upload avatar

1. Create a database table

For convenience, we can create a user table to store user information. The table structure is as follows:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `avatar` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Copy after login

Among them, the avatar field is used to store the path of the user's avatar.

2. Create a user model

In the ThinkPHP framework, we can operate the database through the Model class. Therefore, we need to create a User model first:

<?php
namespace app\index\model;

use think\Model;

class User extends Model
{
    protected $table = &#39;user&#39;;
}
Copy after login

It should be noted that we need to specify the table name as 'user', otherwise ThinkPHP will automatically convert the model class name into the data table name.

3. Create a user controller

Next, we can create a UserController to handle user registration and avatar upload functions:

<?php
namespace app\index\controller;

use app\index\model\User;
use think\Controller;
use think\facade\Request;

class UserController extends Controller
{
    // 用户注册
    public function register()
    {
        if (Request::isPost()) {
            // 处理表单提交
            $user = new User;
            $user->username = Request::param('username');
            $user->password = md5(Request::param('password'));
            
            // 上传头像
            $avatar = Request::file('avatar');
            if ($avatar) {
                $savePath = '/uploads/';
                $saveName = md5($avatar->getOriginalName()) . '.' . $avatar->getExtension();
                $avatar->move('.' . $savePath, $saveName);
                $user->avatar = $savePath . $saveName;
            }
            
            $user->save();
            $this->redirect('/index/Index/index');
        }

        return $this->fetch('user/register');
    }

    // 修改头像
    public function changeAvatar()
    {
        if (Request::isPost()) {
            // 处理表单提交
            $user = User::get(session('user.id'));

            // 删除原头像
            if ($user->avatar) {
                unlink('.' . $user->avatar);
            }

            // 上传新头像
            $avatar = Request::file('avatar');
            if ($avatar) {
                $savePath = '/uploads/';
                $saveName = md5($avatar->getOriginalName()) . '.' . $avatar->getExtension();
                $avatar->move('.' . $savePath, $saveName);
                $user->avatar = $savePath . $saveName;
                $user->save();
            }

            return $this->success('修改头像成功!', '/index/Index/index');
        }

        return $this->fetch('user/change_avatar');
    }
}
Copy after login

The above code implements user registration and avatar upload function. Due to space limitations, this article will not explain it in detail. It should be noted that the saving path of user avatars is in the /public/uploads/ directory.

3. Modify the avatar

1. Modify the user model

In the previous step, we have implemented the upload function of the avatar. However, when the user wants to modify the avatar, we need to delete the original avatar first and then upload the new avatar to the server. Therefore, we need to add a deleteAvatar() method to the User model to delete the user avatar:

public function deleteAvatar()
{
    if ($this->avatar) {
        unlink('.' . $this->avatar);
        $this->avatar = null;
        $this->save();
    }
}
Copy after login

2. Modify the user controller

Next, we can modify the changeAvatar in the UserController () method to support the avatar deletion and upload functions:

public function changeAvatar()
{
    if (Request::isPost()) {
        // 处理表单提交
        $user = User::get(session('user.id'));

        // 删除原头像
        $user->deleteAvatar();

        // 上传新头像
        $avatar = Request::file('avatar');
        if ($avatar) {
            $savePath = '/uploads/';
            $saveName = md5($avatar->getOriginalName()) . '.' . $avatar->getExtension();
            $avatar->move('.' . $savePath, $saveName);
            $user->avatar = $savePath . $saveName;
            $user->save();
        }

        return $this->success('修改头像成功!', '/index/Index/index');
    }

    return $this->fetch('user/change_avatar');
}
Copy after login

The above code implements the user avatar deletion and upload functions. It should be noted that the original avatar needs to be deleted before uploading a new avatar.

4. Summary

Through the above steps, we have successfully implemented the user avatar upload and modification functions in the ThinkPHP framework. Using this basic knowledge, we can further optimize the code and add powerful functions such as avatar cropping and image format conversion to provide users with more complete services.

The above is the detailed content of How to modify user avatar in ThinkPHP framework. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template