首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

ThinkPHP 用戶註冊、登入、留言完整實戰範例(含模型驗證)

     編輯:PHP 綜合知識

本文提供一個完整的 ThinkPHP 專案範例,涵蓋用戶註冊、登入、登出、留言發布/刪除/編輯,並示範模型層自動驗證與自動完成的最佳實踐。

一、資料庫表結構

-- 用戶表
CREATE TABLE `think_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `passwd` varchar(32) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- 留言表
CREATE TABLE `think_content` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userid` int(11) NOT NULL,
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  `addtime` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

二、模型類別

UserModel.class.php(含唯一驗證)

<?php
class UserModel extends Model {
    protected $_validate = [
        ['username', '', '帳號已存在!', 0, 'unique', 1], // 註冊時驗證唯一
    ];
}
?>

ContentModel.class.php(自動驗證+自動完成)

<?php
class ContentModel extends Model {
    protected $_validate = [
        ['title', 'require', '標題必填!'],
        ['content', 'require', '內容必填!'],
    ];

    protected $_auto = [
        ['addtime', 'time', 1, 'function'], // 新增時自動寫入時間戳
    ];
}
?>

三、控制器

UserAction.class.php

<?php
class UserAction extends Action {
    // 顯示註冊頁
    public function register() { $this->display(); }

    // 處理註冊
    public function add() {
        $user = D('User'); // 必須用 D() 載入模型以啟用驗證
        $user->create();
        if ($user->add()) {
            $this->success('註冊成功!', '__APP__/Index/index');
        } else {
            $this->error($user->getError(), '__APP__/User/register');
        }
    }

    // 顯示登入頁
    public function login() { $this->display(); }

    // 處理登入
    public function checklogin() {
        $username = I('post.username');
        $passwd   = I('post.passwd');
        $user = D('User');
        $info = $user->where("username='$username'")->find();

        if ($info) {
            if ($info['passwd'] === $passwd) { // 實際專案請用 password_hash/verify
                Cookie::set('userid', $info['id'], 86400);
                Cookie::set('username', $username, 86400);
                Cookie::set('lastlogintime', time(), 86400);
                $this->success('登入成功!', '__APP__/Index/index');
            } else {
                $this->error('密碼錯誤!', '__APP__/User/login');
            }
        } else {
            $this->error('用戶不存在!', '__APP__/User/login');
        }
    }

    // 登出
    public function loginout() {
        Cookie::delete('username');
        Cookie::delete('userid');
        Cookie::delete('lastlogintime');
        $this->success('已登出', '__APP__/Index/index');
    }
}
?>

IndexAction.class.php(留言 CRUD)

<?php
class IndexAction extends Action {
    // 首頁:列表 + 用戶資訊
    public function index() {
        $content = new ContentModel();
        $list = $content->select();
        $this->assign([
            'list' => $list,
            'username' => Cookie::get('username'),
            'lastlogintime' => Cookie::get('lastlogintime'),
        ]);
        $this->display();
    }

    // 新增留言
    public function insert() {
        $content = new ContentModel();
        if (!$content->create()) {
            $this->error($content->getError());
        }
        $content->userid = Cookie::get('userid');
        $content->add();
        $this->success('發布成功!');
    }

    // 刪除留言
    public function delete() {
        $id = I('get.id', 0, 'intval');
        if (M('Content')->delete($id)) $this->success('刪除成功!');
        else $this->error('刪除失敗!');
    }

    // 編輯頁
    public function edit() {
        $id = I('get.id', 0, 'intval');
        $data = M('Content')->find($id);
        $this->assign('data', $data);
        $this->display();
    }

    // 更新留言
    public function update() {
        $content = new ContentModel();
        $id = I('post.id', 0, 'intval');
        $data = [
            'id' => $id,
            'title' => I('post.title'),
            'content' => I('post.content'),
        ];
        if ($content->save($data)) $this->success('更新成功!');
        else $this->error('更新失敗!');
    }
}
?>

四、關鍵最佳實踐總結

重點說明
D() vs M()D('User') 載入模型類別(支援 _validate/_auto),M('User') 直接操作表(無驗證)
create() 自動映射自動將 $_POST 對應到模型屬性,並觸發驗證
自動完成_auto 設定 addtime 由 time() 函數自動填入
密碼安全範例為明文比對,實務必使用 password_hash()/password_verify()
SQL 注入防護使用 I() 獲取參數,或模型 where() 陣列綁定

五、成功/錯誤跳轉模板

<!-- success.html / error.html -->
<meta http-equiv="refresh" content="2; url='{$jumpUrl}'" />
<div style="margin-top:100px; text-align:center;">
    {$message}<br/>
    2秒後自動跳轉... <a href="{$jumpUrl}">點這裡</a>
</div>

此範例展示了 ThinkPHP 經典 MVC 開發模式,掌握模型驗證、自動完成、Cookie 狀態管理,即可快速構建基礎會員系統。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved