PHP learning notes user registration module user class and verification code class _ PHP Tutorial

Source: Internet
Author: User
PHP learning notes user registration module user class and verification code class. 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 changes and interactions. Therefore, paste the code of chapter 1 and reusable classes to facilitate future access and supply to friends in need.
: User class, including reading and setting databases, and saving change interactions

The code is as follows:


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:

The code is as follows:


// Create user instance
$ U = new User ();
$ U-> username = 'Jack ';
$ U-> password = sha1 ('gogogo ');
$ U-> emailAddr = 'zjczoo @ gmail.com ';
$ U-> save (); // save this user
?>


The code is as follows:


$ 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 =

The code is as follows:


// 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:

The code is as follows:


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:

The code is as follows:


// 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:

The 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;

Bytes. : User class, including reading and setting databases, and saving changes and interactions...

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.