PHP User Registration

Source: Internet
Author: User
Tags php session php basics php regular expression

Objective

Website user registration and login is a very common feature, this section of the textbook to demonstrate how to develop the user registration and login module in PHP.

The key PHP basics to use in this section:

    • PHP has predefined $_post and $_get global variables to accept user forms and URL parameter information, for more information on PHP forms see PHP forms.
    • The PHP regular expression is used to determine if the user's input meets the requirements, and for more information on regular expressions see PHP regular expressions.
    • User Login detection through session to maintain the user's login information, about the session more information see "PHP session" or "PHP Cookie."
Demand analysis

The main functions are divided into four parts: User registration, user login, user exit, User Center.

User Registration

The main functions of user registration are:

    1. Registration Information Form Fill-in interface JavaScript scripts initially detect user-entered registration information.
    2. The registration processing module detects whether the registration information meets the requirements.
    3. Detects if the user name already exists.
    4. The registration information is written to the data table and registered successfully.
User Login

The main functions of user login are:

    1. The login form interface JavaScript script initially detects the login information entered by the user.
    2. The login module checks the user input information with the database data.
    3. If the login information is correct, you are prompted to log on successfully and set the user to login status (session).
    4. The logon information is incorrect, prompting the login to fail and the user can try to log in again.
User exits

The main features of user exit are:

    1. Cancel the session unconditionally.
User Center

The main features of user exit are:

    1. Determine if the user is logged in, and if not, turn to the login screen.
    2. If the login is logged in, the user-related information is read.
Data Sheet Design

According to the function requirement analysis, the user table used to remember the users information needs the following fields:

Field name Data Type Description
Uid Mediumint (8) Primary key, auto-grow
Username CHAR (15) Registered user Name
Password CHAR (32) MD5 Password after encryption
Email varchar (40) User Email
RegDate Int (10) User Registration Timestamp

The table SQL reference is as follows:

CREATE TABLE ' user ' (  ' uid ' mediumint (8) unsigned not NULL auto_increment,  ' username ' char (+) ' NOT null default '  ,  ' password ' char (+) NOT null default ' ',  ' email ' varchar (+) NOT null default ' ',  ' regdate ' int (ten) unsigned Not NULL default ' 0 ',  PRIMARY KEY  (' uid ')) Engine=myisam  default Charset=utf8 auto_increment=1;
Page layout

The functions of each page are as follows:

    • Reg.html: User registration information fill out the form page
    • conn.php: Database connection contains files
    • reg.php: User Registration Handler
    • login.html: User Login Form page
    • login.php: User Login Form page
    • my.php: User Center
Registration page

Reg.html is responsible for collecting the registration information that the user fills in. Only the key snippets are listed in the tutorial, and the complete code is appended to the end of this section.

Registration Form
 <fieldset><legend> User Registration </legend><form name= "RegForm" method= "post" action= "reg.php" Onsubmit= "return Inputcheck (This)" ><p><label for= "username" class= "label" > User name:</label>< Input id= "username" name= "username" type= "text" class= "input"/><span> (required, 3-15 character length, supports Chinese characters, letters, numbers and _) </span ><p/><p><label for= "Password" class= "label" > Password: </label><input id= "password" name= " Password "type=" password "class=" input "/><span> (required, not less than 6 bits) </span><p/><p><label for= "Repass" class= "label" > Duplicate password: </label><input id= "Repass" name= "repass" type= "password" class= "input"/> <p/><p><label for= "Email" class= "label" > E-mail: </label><input id= "email" name= "email" type = "text" class= "input"/><span> (required) </span><p/><p><input type= "Submit" name= "Submit" Value= "Submit Registration" class= "left"/></P></FORM></FIELDSET> 
JavaScript detection Code
<script language=javascript><!--function Inputcheck (RegForm) {  if (RegForm.username.value = = "")  {    alert ("User name cannot be empty!");    RegForm.username.focus ();    return (false);  }  if (RegForm.password.value = = "")  {    alert ("Must set Login password!");    RegForm.password.focus ();    return (false);  }  if (RegForm.repass.value! = RegForm.password.value)  {    alert ("two times password inconsistent!");    RegForm.repass.focus ();    return (false);  }  if (RegForm.email.value = = "")  {    alert ("e-mail cannot be empty!");    RegForm.email.focus ();    return (false);}  } --></script>
CSS Styles
<style type= "Text/css" >    html{font-size:12px;}    fieldset{width:520px; margin:0 Auto;}    Legend{font-weight:bold; font-size:14px;}    Label{float:left; width:70px; margin-left:10px;}    . left{margin-left:80px;}    . input{width:150px;}    Span{color: #666666;} </style>

Registration form:

Database connection
<?php$conn = @mysql_connect ("localhost", "root", "root123"), if (! $conn) {die    ("Connection Database failed:". Mysql_error ());} mysql_select_db ("Test", $conn);//character conversion, read library mysql_query ("Set character set ' GBK '");//write Library mysql_query ("Set names ' GBK '");? >
Registration processing

Reg.php is responsible for handling user registration information.

Registration detection
if (!isset ($_post[' submit ')) {    exit (' illegal access! ');} $username = $_post[' username '); $password = $_post[' password ']; $email = $_post[' Email '];//registration information to determine if (!preg_match ('/^[\w \x80-\xff]{3,15}$/', $username)} {    exit (' ERROR: User name does not meet the requirements. <a href= "Javascript:history.back (-1);" > Return </a> ');} if (strlen ($password) < 6) {    exit (' ERROR: Password length does not meet the requirements. <a href= "Javascript:history.back (-1);" > Return </a> ');} if (!preg_match ('/^w+ ([-+.] w+) *@w+ ([-.] w+) *.w+ ([-.] w+) (*$/', $email)) {    exit (' ERROR: E-mail format is incorrect. <a href= "Javascript:history.back (-1);" > Return </a> ');}

This code first detects whether the POST commits to access the page, next, according to the registration requirements (user name 3-15 character length, support Chinese characters, letters, numbers and _; Password must not be less than 6) to the user submitted registration information to detect. Regular detection is used to detect usernames and e-mail addresses, and for more information about regular expressions, see "Regular Expressions in PHP".

Database interaction
Contains the database connection file include (' conn.php ');//detects if the user name already exists $check_query = mysql_query ("Select uid from user where username= ' $ Username ' limit 1 '), if (Mysql_fetch_array ($check _query)) {    echo ' ERROR: Username ', $username, ' already exists. <a href= "Javascript:history.back (-1);" > Return </a> ';    Exit;} Write Data $password = MD5 ($password), $regdate = Time (), $sql = "INSERT into user (username,password,email,regdate) VALUES (' $ Username ', ' $password ', ' $email ', $regdate) ", if (mysql_query ($sql, $conn)) {    exit (' User registration successful! Click here <a href= "login.html" > Login </a> ');} else {    echo ' Sorry! Failed to add data: ', mysql_error (), ' <br/> ';    Echo ' Click here <a href= "Javascript:history.back (-1);" > Return </a> retry ';}

The code first detects whether the user name already exists and, if present, outputs a hint and terminates the program execution immediately. If the user name does not exist, write the registration information to the database and output the corresponding prompt.

PHP User Login and Exit login page

Login.html is responsible for collecting user-filled login information.

<fieldset><legend> User Login </legend><form name= "LoginForm" method= "post" action= "login.php" Onsubmit= "return Inputcheck (This)" ><p><label for= "username" class= "label" > User name:</label>< Input id= "username" name= "username" type= "text" class= "input"/><p/><p><label for= "password" class= "Label" > Password: </label><input id= "password" name= "password" type= "password" class= "input"/><p/> <p><input type= "Submit" name= "Submit" value= "  OK  " class= "left"/></p></form></ Fieldset>

JavaScript detection and CSS style can refer to reg.html, this section is omitted, you can directly view the final appendix of the complete code.

Login Processing

Login.php is responsible for handling user login and exit actions.

Login if (!isset ($_post[' submit ')) {    exit (' illegal access! ');} $username = Htmlspecialchars ($_post[' username ')), $password = MD5 ($_post[' password ');//contains database connection file include (' conn.php ' );//detect the user name and password correctly $check_query = mysql_query ("Select uid from user where username= ' $username ' and password= ' $password ' Limit 1 "), if ($result = mysql_fetch_array ($check _query)) {    //Login succeeded    $_session[' username '] = $username;    $_session[' userid '] = $result [' uid '];    echo $username, ' Welcome! Enter <a href= "my.php" > User Center </a><br/> ';    Echo ' Click here <a href= "Login.php?action=logout" > Logout </a> Login! <br/> ';    Exit;} else {    exit (' Login failed! Click here <a href= "Javascript:history.back (-1);" > Return </a> retry ');}

This code first confirms that if the user is logged in, it must be a POST action submission. Then according to the user input information to check whether the database is correct, if correct, register session information, otherwise prompt login failed, the user can retry.

The code needs to enable the Session_Start () function at the beginning of the page, see the Exit Processing code section below.

Exit processing

The code that handles the user exit and the code that handles the login are in login.php.

Session_Start ();//Logout Login if ($_get[' action '] = = "Logout") {    unset ($_session[' userid ']);    unset ($_session[' username ');    Echo ' Logout login succeeded! Click here <a href= "login.html" > Login </a> ";    Exit;}

This code is only allowed to be accessed in a login.php?action=logout manner until the code is processed by the user, and other methods are considered to be detecting user logons. See the complete code of the appendix for specific logic.

User Center

my.php is the User Center, listed in the tutorial as a user login detection reference.

<?phpsession_start ();//Check whether login, if not login to the login interface if (!isset ($_session[' userid ')) {    header ("Location:login.html") ;    Exit ();} Include database connection file include (' conn.php '); $userid = $_session[' userid '); $username = $_session[' username ']; $user _query = Mysql_  Query ("SELECT * from user where uid= $userid limit 1"); $row = mysql_fetch_array ($user _query); Echo ' User information: <br/> '; echo ' User id: ', $userid, ' <br/> '; Echo ' username: ', $username, ' <br/> '; Echo ' email: ', $row < ' email ';, ' <br/> '; Echo ' Registration date: ', Date ("y-m-d", $row [' regdate ']), ' <br/> '; Echo ' <a href= ' login.php?action=logout ' > Logout </a > Login <br/> ';? >
Tips
    1. User Registration login involves the user information and database interaction, so pay special attention to the user submitted information can not be illegal information, in this example, the registration section has used regular expression restrictions, the login part is only simple use of htmlspecialchars () processing, practical application can be more stringent.
    2. This tutorial simply demonstrates the user registration and login process, the code is only for learning reference, not directly for the project production.
    3. In this tutorial, you can use a session to manage a user's login success, or use a cookie to manage it, especially for time-limited requirements.
    4. In order to improve the user experience, the user Registration section can be combined with AJAX to detect user-entered information without having to wait for a click to submit and then detect.

PHP User Registration

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.