Home > Backend Development > PHP Tutorial > PHP study notes User registration module user class and verification code class_PHP tutorial

PHP study notes User registration module user class and verification code class_PHP tutorial

WBOY
Release: 2016-07-21 15:24:52
Original
856 people have browsed it

Therefore, I post the code of Chapter 1, the reusable class, for future reference and for providing to friends in need.
: User class, including reading and setting the database, and saving changes interaction

Copy code The code is as follows:

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();
}
}
}
}
?>

如何使用:
复制代码 代码如下:

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

Copy code The code is as follows:

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

: Verification code type: This is relatively simple, you can add a picture yourself==
Copy code The code is as follows:

//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);
?>

In addition, this class uses the random_text() function, the code is as follows:
Copy the code The code is as follows:

< ;?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;
}
?>

Connect database class:
Copy code The code is as follows:

// 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 statement:
Copy code Code As follows:

DROP TABLE IF EXISTS WROX_PENDING;
DROP TABLE IF EXISTS WROX_USER; ) 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 NOT CHAR(10)
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; >

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324215.htmlTechArticleSo, post the code of the first chapter, the reusable class, for future reference and for friends in need. . : User class, including reading and setting the database, and saving changes interaction...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template