早起的菜鸟

FEer---思考,感悟,总结,翻译,分享

导航

【PHP学习笔记】用户注册模块用户类以及验证码类

最近正在学习《PHP&MySQL范例精解》,刚刚看到第一张,关于用户注册模块的设计,这本书提供了很多可重用类,便于用于其它项目中。

所以,把第一章,可重用类的代码贴出来,便于以后查阅以及供给有需要的朋友。

1:User类,包括读取和设置数据库,以及保存更改交互

  

  1 <?php
2 class User{
3 private $uid;
4 private $fields;
5
6 public function __construct(){
7 $this->uid=null;
8 $this->fields=array('username'=>'','password'=>'','emailAddr'=>'','isActive'=>false);
9 }
10
11 public function __get($field){
12 if($field=='userId'){
13 return $this->uid;
14 }else{
15 return $this->fields[$field];
16 }
17 }
18
19 public function __set($field,$value){
20 if(array_key_exists($field,$this->fields)){
21 $this->fields[$field]=$value;
22 }
23 }
24
25 //return if username is valid format
26 public static function validateUsername($username){
27 return preg_match('/^[A-Z0-9]{2,20}$/i',$username);
28 }
29
30 //return if email address is valid format
31 public static function validateEmailAddr($email){
32 return filter_var($email,FILTER_VALIDATE_EMAIL);
33 }
34
35 //return an object populated based on the record‘s user id
36 public static function getById($user_id){
37 $user=new User();
38 $query=sprintf('SELECT USERNAME,PASSWORD,EMAIL_ADDR,IS_ACTIVE '.
39 'FROM %sUSER WHERE USER_ID=%d',DB_TBL_PREFIX,$user_id);
40 $result=mysql_query($query,$GLOBALS['DB']);
41 if(mysql_num_rows($result)){
42 $row=mysql_fetch_assoc($result);
43 $user->username=$row['USERNAME'];
44 $user->password=$row['PASSWORD'];
45 $user->emailAddr=$row['EMAIL_ADDR'];
46 $user->isActive=$row['IS_ACTIVE'];
47 ChromePhp::log($user_id);
48 $user->uid=$user_id;
49 }
50 mysql_free_result($result);
51 return $user;
52 }
53
54 //return an object populated based on the record’s username
55 public static function getByUsername($username){
56 $user=new User();
57 $query=sprintf('SELECT USER_ID,PASSWORD,EMAIL_ADDR,IS_ACTIVE '.
58 'FROM %sUSER WHERE USERNAME="%s"',DB_TBL_PREFIX,mysql_real_escape_string($username,$GLOBALS['DB']));
59 $result=mysql_query($query,$GLOBALS['DB']);
60 if(mysql_num_rows($result)){
61 $row=mysql_fetch_assoc($result);
62 $user->username=$username;
63 $user->password=$row['PASSWORD'];
64 $user->emailAddr=$row['EMAIL_ADDR'];
65 $user->isActive=$row['IS_ACTIVE'];
66 $user->uid=$row['USER_ID'];
67 }
68 mysql_free_result($result);
69 return $user;
70 }
71
72 //save the record to the database
73 public function save(){
74 //update existing user's information
75 if($this->uid){
76 $query = sprintf('UPDATE %sUSER SET USERNAME = "%s", ' .
77 'PASSWORD = "%s", EMAIL_ADDR = "%s", IS_ACTIVE = %d ' .
78 'WHERE USER_ID = %d',
79 DB_TBL_PREFIX,
80 mysql_real_escape_string($this->username, $GLOBALS['DB']),
81 mysql_real_escape_string($this->password, $GLOBALS['DB']),
82 mysql_real_escape_string($this->emailAddr, $GLOBALS['DB']),
83 $this->isActive,
84 $this->userId);
85 return mysql_query($query, $GLOBALS['DB']);
86 }else{
87 //create a new user
88 $query=sprintf('INSERT INTO %sUSER(USERNAME,PASSWORD,' .
89 'EMAIL_ADDR,IS_ACTIVE) VALUES ("%s","%s","%s",%d)',
90 DB_TBL_PREFIX,
91 mysql_real_escape_string($this->username,$GLOBALS['DB']),
92 mysql_real_escape_string($this->password,$GLOBALS['DB']),
93 mysql_real_escape_string($this->emailAddr,$GLOBALS['DB']),
94 $this->isActive);
95 if(mysql_query($query,$GLOBALS['DB'])){
96 $this->uid=mysql_insert_id($GLOBALS['DB']);
97 return true;
98 }else{
99 return false;
100 }
101 }
102 }
103
104 //set the record as inactive and return an activation token
105 public function setInactive(){
106 $this->isActive=false;
107 $this->save();
108 $token=random_text(5);
109 $query=sprintf('INSERT INTO %sPENDING (USER_ID,TOKEN)' .
110 'VALUES (%d,"%s")',DB_TBL_PREFIX,$this->uid,$token);
111 return (mysql_query($query,$GLOBALS['DB']))?$token:false;
112 }
113
114 //clear the user's pending status and set the record as active
115 public function setActive($token){
116 $query=sprintf('SELECT TOKEN FROM %sPENDING WHERE USER_ID=%d ' .
117 'AND TOKEN="%s"',DB_TBL_PREFIX,$this->uid,mysql_real_escape_string($token,$GLOBALS['DB']));
118 $result=mysql_query($query,$GLOBALS['DB']);
119 if(!mysql_num_rows(($result))){
120 mysql_free_result($result);
121 return false;
122 }else{
123 mysql_free_result($result);
124 $query=sprintf('DELETE FROM %sPENDING WHERE USER_ID=%d ' .
125 'AND TOKEN="%s"',DB_TBL_PREFIX,$this->uid,mysql_real_escape_string($token,$GLOBALS['DB']));
126 if(!mysql_query($query,$GLOBALS['DB'])){
127 return false;
128 }else{
129 $this->isActive=true;
130 return $this->save();
131 }
132 }
133 }
134 }
135 ?>

  如何使用:

<?php
//create user instance
$u=new User();
$u->username='jack';
$u->password=sha1('gogo');
$u->emailAddr='zjczoo@gmail.com';
$u->save();//save this user
?>

  

1 <?php
2 $u=User::getByUsername('jack');//update user('jack')
3 $u->password=sha1('newgogo');
4 $u->save();//save new jack
5 ?>

  

 2:验证码类:这个比较简单,你可以自己加个图片==

 1 <?php
2 //must start or continue session and save CAPTCHA string in $_SESSION for
3 //it to be available to other requests
4 if(!isset($_SESSION)){
5 session_start();
6 header('Cache-control:private');
7 }
8
9 //create a 65*20 pixel image
10 $width=65;
11 $height=20;
12 $image=imagecreate(65,20);
13
14 //fill the image background color
15 $bg_color=imagecolorallocate($image,0x33,0x66,0xFF);
16 imagefilledrectangle($image,0,0,$width,$height,$bg_color);
17
18 //fetch random text
19 $text=random_text(5);
20
21 //determine x and y coordinates for centering text
22 $font=5;
23 $x=imagesx($image)/2-strlen($text)*imagefontwidth($font)/2;
24 $y=imagesy($image)/2-imagefontheight($font)/2;
25
26 //write text on image
27 $fg_color=imagecolorallocate($image,0xFF,0xFF,0xFF);
28 imagestring($image,$font,$x,$y,$text,$fg_color);
29
30 //save the CAPTCHA string for later comparison
31 $_SESSION['captcha']=$text;
32
33 //output the image
34 header('Content-type:image/png');
35 imagepng($image);
36
37 imagedestroy($image);
38 ?>

  另外,该类用到了random_text()函数,代码如下:

 1 <?php
2 function random_text($count,$rm_similar=false){
3 $chars=array_flip(array_merge(range(0,9),range('A','Z')));
4
5 if($rm_similar){
6 unset($chars[0],$chars[1],$chars[2],$chars[5],$chars[8],$chars['B'],$chars['I'],$chars['O'],$chars['Q'],$chars['S'],$chars['V'],$chars['Z']);
7 }
8
9 for($i=0,$text='';$i<$count;$i++){
10 $text.=array_rand($chars);
11 }
12 return $text;
13 }
14 ?>

  

   连接数据库类:

<?php
// database connection and schema constants
define(
'DB_HOST', 'localhost');
define(
'DB_USER', 'username');
define(
'DB_PASSWORD', 'yourpassword');
define(
'DB_SCHEMA', 'WROX_DATABASE');
define(
'DB_TBL_PREFIX', 'WROX_');

// establish a connection to the database server
if (!$GLOBALS['DB'] = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD))
{
die(
'Error: Unable to connect to database server.');
}
if (!mysql_select_db(DB_SCHEMA, $GLOBALS['DB']))
{
mysql_close($GLOBALS
['DB']);
die(
'Error: Unable to select database schema.');
}
?
>

  

   sql语句:

 1 DROP TABLE IF EXISTS WROX_PENDING;
2 DROP TABLE IF EXISTS WROX_USER;
3
4 CREATE TABLE WROX_USER (
5 USER_ID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
6 USERNAME VARCHAR(20) NOT NULL,
7 PASSWORD CHAR(40) NOT NULL,
8 EMAIL_ADDR VARCHAR(100) NOT NULL,
9 IS_ACTIVE TINYINT(1) DEFAULT 0,
10
11 PRIMARY KEY (USER_ID)
12 )
13 ENGINE=MyISAM DEFAULT CHARACTER SET gb2312
14 COLLATE gb2312_chinese_ci AUTO_INCREMENT=0;
15
16 CREATE TABLE WROX_PENDING (
17 USER_ID INTEGER UNSIGNED PRIMARY KEY NOT NULL,
18 TOKEN CHAR(10) NOT NULL,
19 CREATED_DATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
20
21 FOREIGN KEY (USER_ID)
22 REFERENCES WROX_USER(USER_ID)
23 )
24 ENGINE=MyISAM DEFAULT CHARACTER SET gb2312
25 COLLATE gb2312_chinese_ci;

  

  

posted on 2011-09-18 16:49  早起的菜鸟  阅读(928)  评论(0编辑  收藏  举报