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 相关文章推荐
用PHP编程语言开发动态WAP页面
Oct 09 PHP
DISCUZ 论坛管理员密码忘记的解决方法
May 14 PHP
PHP STRING 陷阱原理说明
Jul 24 PHP
PHP限制页面只能在微信自带浏览器访问的代码
Jan 15 PHP
两级联动select刷新后其值保持不变的实现方法
Jan 27 PHP
php使用指定编码导出mysql数据到csv文件的方法
Mar 31 PHP
详解PHP数组赋值方法
Nov 07 PHP
PHP入门教程之PHP操作MySQL的方法分析
Sep 11 PHP
ThinkPHP 模板substr的截取字符串函数详解
Jan 09 PHP
PHP中实现中文字串截取无乱码的解决方法
May 29 PHP
php实现将数据做成json的格式给前端使用
Aug 21 PHP
php使用fputcsv实现大数据的导出操作详解
Feb 27 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之变量、常量学习笔记
2008/03/27 PHP
用php将任何格式视频转为flv的代码
2009/09/03 PHP
Mysql的Root密码忘记,查看或修改的解决方法(图文介绍)
2013/06/14 PHP
关于php操作mysql执行数据库查询的一些常用操作汇总
2013/06/24 PHP
PHP+jQuery 注册模块的改进(一):验证码存入SESSION
2014/10/14 PHP
php实现支持中文的文件下载功能示例
2017/08/30 PHP
javascript 实现父窗口引用弹出窗口的值的脚本
2007/08/07 Javascript
推荐一些非常不错的javascript学习资源站点
2007/08/29 Javascript
让FireFox支持innerText的实现代码
2009/12/01 Javascript
jQuery对象与DOM对象之间的转换方法
2010/04/15 Javascript
js通过元素class名字获取元素集合的具体实现
2014/01/06 Javascript
Egret引擎开发指南之创建项目
2014/09/03 Javascript
Nodejs学习笔记之Global Objects全局对象
2015/01/13 NodeJs
原生js实现类似弹窗抖动效果
2015/04/02 Javascript
Nodejs抓取html页面内容(推荐)
2016/08/11 NodeJs
使用InstantClick.js让页面提前加载200ms
2017/09/12 Javascript
原生js实现淘宝放大镜效果
2020/10/28 Javascript
layui动态加载多表头的实例
2019/09/05 Javascript
[03:20]次级联赛厮杀超职业 现超级兵对拆世纪大战
2014/10/30 DOTA
Django使用详解:ORM 的反向查找(related_name)
2018/05/30 Python
使用pandas实现csv/excel sheet互相转换的方法
2018/12/10 Python
Python实现最常见加密方式详解
2019/07/13 Python
python实现大文本文件分割
2019/07/22 Python
python实现删除列表中某个元素的3种方法
2020/01/15 Python
Django ORM实现按天获取数据去重求和例子
2020/05/18 Python
Python JSON常用编解码方法代码实例
2020/09/05 Python
在pycharm创建scrapy项目的实现步骤
2020/12/01 Python
Python文件名匹配与文件复制的实现
2020/12/11 Python
使用css3制作动感导航条示例
2014/01/26 HTML / CSS
HTML5 Canvas 实现圆形进度条并显示数字百分比效果示例
2017/08/18 HTML / CSS
荷兰皇家航空公司中国官网:KLM中国
2017/12/13 全球购物
高校教师自荐信范文
2014/03/13 职场文书
学校宣传标语
2014/06/18 职场文书
2016年企业安全生产月活动总结
2016/04/06 职场文书
交通安全宣传标语(100条)
2019/08/22 职场文书
教你用python控制安卓手机
2021/05/13 Python