PHP learning notes User Registration Module User and Verification Code

Source: Internet
Author: User

Therefore, paste the code of the first chapter and reusable classes to facilitate future reference and supply to friends who need them.
: User class, including reading and setting databases, and saving change interactions
Copy codeThe Code is as follows:
<? Php
Class User {
Private $ uid;
Private $ fields;
Public function _ construct (){
$ This-> uid = null;
$ This-> fields = array ('username' => '', 'Password' =>'', 'emailadd' => '', '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 _ activity'];
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 _ activity'];
$ 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", % 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 ();
}
}
}
}
?>

How to use:
Copy codeThe Code is as follows:
<? Php
// Create user instance
$ U = new User ();
$ U-> username = 'jack ';
$ U-> password = sha1 ('gogogo ');
$ U-> emailAddr = 'zjczoo @ gmail.com ';
$ U-> save (); // save this user
?>

Copy codeThe Code is as follows:
<? Php
$ U = User: getByUsername ('jack'); // update user ('jack ')
$ U-> password = sha1 ('newgogogo ');
$ U-> save (); // save new jack
?>

: Verification Code Class: This is relatively simple. You can add an image =
Copy codeThe Code is as follows:
<? Php
// Must start or continue session and save CAPTCHA string in $ _ SESSION
// 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 codeThe 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;
}
?>

Database connection:
Copy codeThe Code is as follows:
<? Php
// Database connection and schema constants
Define ('db _ host', 'localhost ');
Define ('db _ user', 'username ');
Define ('db _ password', 'yourpassword ');
Define ('db _ scheme', '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 codeThe Code is as follows:
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;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.