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


Posted in PHP onSeptember 20, 2011

所以,把第一章,可重用类的代码贴出来,便于以后查阅以及供给有需要的朋友。
:User类,包括读取和设置数据库,以及保存更改交互

<?php 
class User{ 
private $uid; 
private $fields; 
public function __construct(){ 
$this->uid=null; 
$this->fields=array('username'=>'','password'=>'','emailAddr'=>'','isActive'=>false); 
} 
public function __get($field){ 
if($field=='userId'){ 
return $this->uid; 
}else{ 
return $this->fields[$field]; 
} 
} 
public function __set($field,$value){ 
if(array_key_exists($field,$this->fields)){ 
$this->fields[$field]=$value; 
} 
} 
//return if username is valid format 
public static function validateUsername($username){ 
return preg_match('/^[A-Z0-9]{2,20}$/i',$username); 
} 
//return if email address is valid format 
public static function validateEmailAddr($email){ 
return filter_var($email,FILTER_VALIDATE_EMAIL); 
} 
//return an object populated based on the record‘s user id 
public static function getById($user_id){ 
$user=new User(); 
$query=sprintf('SELECT USERNAME,PASSWORD,EMAIL_ADDR,IS_ACTIVE '. 
'FROM %sUSER WHERE USER_ID=%d',DB_TBL_PREFIX,$user_id); 
$result=mysql_query($query,$GLOBALS['DB']); 
if(mysql_num_rows($result)){ 
$row=mysql_fetch_assoc($result); 
$user->username=$row['USERNAME']; 
$user->password=$row['PASSWORD']; 
$user->emailAddr=$row['EMAIL_ADDR']; 
$user->isActive=$row['IS_ACTIVE']; 
ChromePhp::log($user_id); 
$user->uid=$user_id; 
} 
mysql_free_result($result); 
return $user; 
} 
//return an object populated based on the record's username 
public static function getByUsername($username){ 
$user=new User(); 
$query=sprintf('SELECT USER_ID,PASSWORD,EMAIL_ADDR,IS_ACTIVE '. 
'FROM %sUSER WHERE USERNAME="%s"',DB_TBL_PREFIX,mysql_real_escape_string($username,$GLOBALS['DB'])); 
$result=mysql_query($query,$GLOBALS['DB']); 
if(mysql_num_rows($result)){ 
$row=mysql_fetch_assoc($result); 
$user->username=$username; 
$user->password=$row['PASSWORD']; 
$user->emailAddr=$row['EMAIL_ADDR']; 
$user->isActive=$row['IS_ACTIVE']; 
$user->uid=$row['USER_ID']; 
} 
mysql_free_result($result); 
return $user; 
} 
//save the record to the database 
public function save(){ 
//update existing user's information 
if($this->uid){ 
$query = sprintf('UPDATE %sUSER SET USERNAME = "%s", ' . 
'PASSWORD = "%s", EMAIL_ADDR = "%s", IS_ACTIVE = %d ' . 
'WHERE USER_ID = %d', 
DB_TBL_PREFIX, 
mysql_real_escape_string($this->username, $GLOBALS['DB']), 
mysql_real_escape_string($this->password, $GLOBALS['DB']), 
mysql_real_escape_string($this->emailAddr, $GLOBALS['DB']), 
$this->isActive, 
$this->userId); 
return mysql_query($query, $GLOBALS['DB']); 
}else{ 
//create a new user 
$query=sprintf('INSERT INTO %sUSER(USERNAME,PASSWORD,' . 
'EMAIL_ADDR,IS_ACTIVE) VALUES ("%s","%s","%s",%d)', 
DB_TBL_PREFIX, 
mysql_real_escape_string($this->username,$GLOBALS['DB']), 
mysql_real_escape_string($this->password,$GLOBALS['DB']), 
mysql_real_escape_string($this->emailAddr,$GLOBALS['DB']), 
$this->isActive); 
if(mysql_query($query,$GLOBALS['DB'])){ 
$this->uid=mysql_insert_id($GLOBALS['DB']); 
return true; 
}else{ 
return false; 
} 
} 
} 
//set the record as inactive and return an activation token 
public function setInactive(){ 
$this->isActive=false; 
$this->save(); 
$token=random_text(5); 
$query=sprintf('INSERT INTO %sPENDING (USER_ID,TOKEN)' . 
'VALUES (%d,"%s")',DB_TBL_PREFIX,$this->uid,$token); 
return (mysql_query($query,$GLOBALS['DB']))?$token:false; 
} 
//clear the user's pending status and set the record as active 
public function setActive($token){ 
$query=sprintf('SELECT TOKEN FROM %sPENDING WHERE USER_ID=%d ' . 
'AND TOKEN="%s"',DB_TBL_PREFIX,$this->uid,mysql_real_escape_string($token,$GLOBALS['DB'])); 
$result=mysql_query($query,$GLOBALS['DB']); 
if(!mysql_num_rows(($result))){ 
mysql_free_result($result); 
return false; 
}else{ 
mysql_free_result($result); 
$query=sprintf('DELETE FROM %sPENDING WHERE USER_ID=%d ' . 
'AND TOKEN="%s"',DB_TBL_PREFIX,$this->uid,mysql_real_escape_string($token,$GLOBALS['DB'])); 
if(!mysql_query($query,$GLOBALS['DB'])){ 
return false; 
}else{ 
$this->isActive=true; 
return $this->save(); 
} 
} 
} 
} 
?>

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

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

:验证码类:这个比较简单,你可以自己加个图片==
<?php 
//must start or continue session and save CAPTCHA string in $_SESSION for 
//it to be available to other requests 
if(!isset($_SESSION)){ 
session_start(); 
header('Cache-control:private'); 
} 
//create a 65*20 pixel image 
$width=65; 
$height=20; 
$image=imagecreate(65,20); 
//fill the image background color 
$bg_color=imagecolorallocate($image,0x33,0x66,0xFF); 
imagefilledrectangle($image,0,0,$width,$height,$bg_color); 
//fetch random text 
$text=random_text(5); 
//determine x and y coordinates for centering text 
$font=5; 
$x=imagesx($image)/2-strlen($text)*imagefontwidth($font)/2; 
$y=imagesy($image)/2-imagefontheight($font)/2; 
//write text on image 
$fg_color=imagecolorallocate($image,0xFF,0xFF,0xFF); 
imagestring($image,$font,$x,$y,$text,$fg_color); 
//save the CAPTCHA string for later comparison 
$_SESSION['captcha']=$text; 
//output the image 
header('Content-type:image/png'); 
imagepng($image); 
imagedestroy($image); 
?>

另外,该类用到了random_text()函数,代码如下:
<?php 
function random_text($count,$rm_similar=false){ 
$chars=array_flip(array_merge(range(0,9),range('A','Z'))); 
if($rm_similar){ 
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']); 
} 
for($i=0,$text='';$i<$count;$i++){ 
$text.=array_rand($chars); 
} 
return $text; 
} 
?>

连接数据库类:
<?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语句:
DROP TABLE IF EXISTS WROX_PENDING; 
DROP TABLE IF EXISTS WROX_USER; 
CREATE TABLE WROX_USER ( 
USER_ID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, 
USERNAME VARCHAR(20) NOT NULL, 
PASSWORD CHAR(40) NOT NULL, 
EMAIL_ADDR VARCHAR(100) NOT NULL, 
IS_ACTIVE TINYINT(1) DEFAULT 0, 
PRIMARY KEY (USER_ID) 
) 
ENGINE=MyISAM DEFAULT CHARACTER SET gb2312 
COLLATE gb2312_chinese_ci AUTO_INCREMENT=0; 
CREATE TABLE WROX_PENDING ( 
USER_ID INTEGER UNSIGNED PRIMARY KEY NOT NULL, 
TOKEN CHAR(10) NOT NULL, 
CREATED_DATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 
FOREIGN KEY (USER_ID) 
REFERENCES WROX_USER(USER_ID) 
) 
ENGINE=MyISAM DEFAULT CHARACTER SET gb2312 
COLLATE gb2312_chinese_ci;
PHP 相关文章推荐
NOD32 v2.70.32 简体中文封装版 提供下载了
Feb 27 PHP
配置Apache2.2+PHP5+CakePHP1.2+MySQL5运行环境
Apr 25 PHP
PHP初学者常见问题集合 修正版(21问答)
Mar 23 PHP
PHP 文件缓存的性能测试
Apr 25 PHP
PHP中extract()函数的定义和用法
Aug 17 PHP
PHP实现的交通银行网银在线支付接口ECSHOP插件和使用例子
May 10 PHP
单台服务器的PHP进程之间实现共享内存的方法
Jun 13 PHP
将酷狗krc歌词解析并转换为lrc歌词php源码
Jun 20 PHP
PHP关于htmlspecialchars、strip_tags、addslashes的解释
Jul 04 PHP
PHP批量去除BOM头代码分享
Jun 26 PHP
php实现简单的守护进程创建、开启与关闭操作
Aug 13 PHP
PHP安装扩展mcrypt以及相关依赖项深入讲解
Mar 04 PHP
PHP无刷新上传文件实现代码
Sep 19 #PHP
PHP通过正则表达式下载图片到本地的实现代码
Sep 19 #PHP
PHP下利用shell后台运行PHP脚本,并获取该脚本的Process ID的代码
Sep 19 #PHP
php去除重复字的实现代码
Sep 16 #PHP
PHP与SQL注入攻击防范小技巧
Sep 16 #PHP
php中判断字符串是否全是中文或含有中文的实现代码
Sep 16 #PHP
php中模拟POST传递数据的两种方法分享
Sep 16 #PHP
You might like
php防止sql注入示例分析和几种常见攻击正则表达式
2014/01/12 PHP
php递归实现无限分类的方法
2015/07/28 PHP
smarty简单应用实例
2015/11/03 PHP
对比PHP对MySQL的缓冲查询和无缓冲查询
2016/07/01 PHP
九种js弹出对话框的方法总结
2013/03/12 Javascript
js判断当页面无法回退时关闭网页否则就history.go(-1)
2014/08/07 Javascript
JavaScript中的对象序列化介绍
2014/12/30 Javascript
DOM基础教程之事件对象
2015/01/20 Javascript
JavaScript调用浏览器打印功能实例分析
2015/07/17 Javascript
jquery实现用户信息修改验证输入方法汇总
2015/07/18 Javascript
js实现适用于素材网站的黑色多级菜单导航条效果
2015/08/24 Javascript
整理Javascript基础入门学习笔记
2015/11/29 Javascript
jQuery height()、innerHeight()、outerHeight()函数的区别详解
2016/05/23 Javascript
AngularJS使用ng-options指令实现下拉框
2016/08/23 Javascript
JS监控关闭浏览器操作的实例详解
2017/09/12 Javascript
vue-cli中打包图片路径错误的解决方法
2017/10/26 Javascript
AngularJS 表单验证手机号的实例(非必填)
2017/11/12 Javascript
微信小程序表单验证功能完整实例
2017/12/01 Javascript
Angular5中提取公共组件之radio list的实例代码
2018/07/10 Javascript
vue-cli系列之vue-cli-service整体架构浅析
2019/01/14 Javascript
js中Array对象的常用遍历方法详解
2019/01/17 Javascript
使用Vue实现移动端左滑删除效果附源码
2019/05/16 Javascript
了解前端理论:rscss和rsjs
2019/05/23 Javascript
浅谈layui里的上传控件问题
2019/09/26 Javascript
Angular处理未可知异常错误的方法详解
2021/01/17 Javascript
[00:12]DAC2018 no[o]ne亮相SOLO赛 他是否如他的id一样无人可挡?
2018/04/06 DOTA
Python优先队列实现方法示例
2017/09/21 Python
python实现SOM算法
2018/02/23 Python
Python一行代码实现快速排序的方法
2019/04/30 Python
Python内置函数property()如何使用
2020/09/01 Python
HTML5 textarea高度自适应的两种方案
2020/04/08 HTML / CSS
阿根廷在线宠物商店:Puppis
2018/03/23 全球购物
瑞典廉价机票预订网站:Seat24
2018/06/19 全球购物
Probikekit欧盟:在线公路自行车专家
2019/07/12 全球购物
2014全国两会心得体会
2014/03/17 职场文书
质监局领导班子对照检查材料思想汇报
2014/09/27 职场文书