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

所以,把第一章,可重用类的代码贴出来,便于以后查阅以及供给有需要的朋友。
: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程序内部post数据的方法 - 2015-06-30 10:06:39

本文实例讲述了php程序内部post数据的方法。分享给大家供大家参考。具体实现方法如下: $postData = array();$postData['data1'] = "testdata1";$postData['data2'] = "testdata2";$postData['data3'] = "testdata3";$url='http://yourdomain/do.php';$str="";foreach ($postData as $k=$v){ $str.= "$k=".urlencod
解决办法: 在php.ini中将max_input_vars调大改为5000就可以了 原因追查: from的enctype="multipart/form-data" php版本5.6.6 问题:部分POST数据接收不到 追源代码发现是php中max_input_vars配置造成的; 相关函数为rfc1867_post_handler,如果超过长度,则不会调用safe_php_register_variable来进行变量注册 相关堆栈如下 复制代码 代码如下: #0 rfc1867_post_handle

PHP实现事件机制实例分析 - 2015-06-30 10:06:02

本文实例讲述了PHP实现事件机制的方法。分享给大家供大家参考。具体分析如下: 内置了事件机制的语言不多,php也没有提供这样的功能。事件(Event)说简单了就是一个Observer模式,实现起来很容易。但是有所不同的是,事件的监听者谁都可以加,但是只能由直接包含它的对象触发。这就有一点点难度了。php有一个debug_backtrace函数,可以得到当前的调用栈,由此可以找到判断调用事件触发函数的对象是不是直接包含它的对象的办法。 ?php/*** 事件** @author xiezhenye xiez

PHP魔术方法的使用示例 - 2015-06-30 10:06:02

① __get/__set:将对象的属性进行接管 当访问一个不存在的对象属性时: index.php 复制代码 代码如下: ?php define('BASEDIR',__DIR__); //定义根目录常量 include BASEDIR.'/Common/Loader.php'; spl_autoload_register('\\Common\\Loader::autoload'); $obj = new \Common\Object(); //在php中访问一个不存在的对象属性时 echo $obj-

mac下安装nginx和php - 2015-06-30 09:06:59

一、前话: 1.1、环境选择: 重新在mac上配置php,原本mac上就自带有apach、php以及pgsql,如果图简单的话,直接用就可以了,不过在安装前我仔细思考了一下几个问题: 选apache还是nginx:两个我了解的都比较少,相对而言我接触nginx比较多,服务器用的也是nginx,没办法谁叫nginx负载高呢。为了更好的接触nginx的环境,我决定还是统一下环境,方便今后使用,这是这次的主要关键; 安装php:Mac os自带了php,好像是5.3.8,版本比较落后,不过这不碍事,因为以前我都是

php生成PDF格式文件并且加密 - 2015-06-30 09:06:26

项目需求:php生成pdf文件,并且把该文件加密或设置访问密码 开源的TCPDF是基于PHP的一套类库,它能够很好的生成PDF格式的文档。并且支持文件加密,在目前的开源PHP框架、系统、应用中也使用得很广。这里是设置PDF文档的相关属性的方法原型,其中就可以设置密码 TCPDF::SetProtection ($permissions = array('print', 'modify', 'copy', 'annot-forms', 'fill-forms', 'extract', 'assemble',
一、数组遍历的3个方法介绍 1. foreach() foreach()是一个用来遍历数组中数据的最简单有效的方法。 #example1: 复制代码 代码如下: ?php $colors= array('red','blue','green','yellow'); foreach ($colorsas$color){ echo "Do you like $color? br /"; } ? 显示结果: Do you like red? Do you like blue? Do you like green

解析ajax事件的调用顺序 - 2015-06-30 07:06:11

jquery的ajax请求方法: 复制代码 代码如下: $.ajax({ type: "GET", dateType:"html", url: "index.html", error: function(msg) { alert("error"); }, complete: function(msg) { alert("complete"); }, success: function(msg) { alert("success"); } }); jquery中各个事件执行顺序如下: 1.ajaxStart
本文实例讲述了php使用CURL不依赖COOKIEJAR获取COOKIE的方法。分享给大家供大家参考。具体分析如下: PHP中CURL类是一个非常牛逼的工具类,具体怎么牛逼就不
本文实例讲述了php判断一个数组是否为有序的方法。分享给大家供大家参考。具体分析如下: 这段代码的时间复杂度为O(n) ?php function JudegSortArray($array) { if ($array [0] $array [1]) { $flag = 1; } else { $flag = 0; } $temp = $flag; $len = count ( $array ); for($i = 1; $i $len; $i ++) { if ($flag == 0) { if ($a