PHP User Login Verification Module

Source: Internet
Author: User
This article introduces the content of the PHP user Login verification module, has a certain reference value, now share to everyone, the need for friends can refer to

Implement User Login

>>>1 Creating Login Forms

The HTML code for the login form is as follows:

Save the above code as a login.php file and run it in the browser.

>>>2 Verifying the login name and password

After the user enters login information in the login form, the data is submitted back to this page login.php for processing, and the following code is added to Login.php's header to verify that the user name and password are correct. The login.php code changes as follows:


<?phprequire_once (' common.php '); Introduce a common file that implements the code for SQL injection vulnerability checking $username = Trim ($_post[' username '));//Obtain the client-submitted password and encrypt the conversion with the MD5 () function for subsequent validation $pwd = MD5 ($_post [' pwd ']); /set an error message variable to determine if an error occurred//and an error message is displayed on the client. The initial value is null $errmsg = ", if (!empty ($username)) {//user fills in data to perform database operation//----------------------------------------------------- ----//data validation, the empty () function determines whether the contents of the variable are empty if (empty ($username)) {$errmsg = ' data input is incomplete ';} ---------------------------------------------------------if (empty ($errmsg)) {//$errmsg NULL Description Previous validation passed// Call Mysqli's constructor to establish a connection while choosing to use the database ' test ' $db = @new mysqli ("127.0.0.1", "Developer", "123456", "test");//Check database connection if (mysqli_ Connect_errno ()) {$errmsg = "database connection failed!\n";} else {//query the database to see if the user name and password are correct $sql = "SELECT * from T_user WHERE f_username= ' $username ' and f_password= ' $pwd '"; $rs = $db->q Uery ($sql);//$rs->num_rows to determine if the above execution results contain records, a record of successful login if ($rs && $rs->num_rows > 0) {// In the actual application can use the previously mentioned redirection function to go to the homepage $errmsg = "Login successful!";} else {$errmsg = "user name or password is incorrect, login failed!";} Close database connection $db->close ();}}? ><Html>

The Bold section is the newly added code, and most statements are commented in detail. It is worth noting that the code added in the HTML form, where the first row of the cell is added to the PHP code to output the server-side process can occur errors or prompts, in addition to the user name of the input box tag of the Value property added PHP code to output the last committed user name, Users who cannot log on because they have entered a password incorrectly only need to enter a password when retrying.
Run login.php again and enter data into the form to try to sign in.

>>>3 Update User login information

In User Information table T_user, the F_logintimes field is used to record the number of user logins, f_lasttime fields are used to record the last time the user logged on, and the F_login field is used to record the IP of the user's last login. The information in the database is mainly for the management to provide statistics user login number and user geographical distribution convenience. This data is updated every time the user logs in, and the code to update the data is added below.
Open the login.php file and change the PHP code on its head to the following:

<?php......if ($rs && $rs->num_rows > 0) {//In practice you can use the previously mentioned redirection feature to go to page 4th/6 $errmsg = "Login successful!"; /update User login information $ip = $_server[' remote_addr ']; Get the client's Ip$sql = "UPDATE t_user SET f_logintimes = f_logintimes + 1,"; $sql. = "F_lasttime=now (), f_loginip= ' $ip '"; $sql. = "WHERE f_username= ' $username '"; $db->query ($sql);} else {$errmsg = "user name or password is incorrect, login failed!";} ......? >

The bold section above is the newly added code, which first obtains the client's IP address from the automatic global variable $_server, then constructs the SQL statement and executes the statement to update the user logon information. It is important to note that the assignment of f_lasttime in this SQL statement is implemented by invoking the internal function of MySQL now (), and the current () function of the MySQL is returned on the server at the present time.

>>>4 Save user information with session

The

HTTP protocol is stateless. What it does is simply send the request to the server, and get the data from the server, except that, even if two times the same PHP file is requested, it does not think there is any connection between the two requests.
Because of the stateless State of the HTTP protocol, this makes it impossible to share information between two different requests, such as the inability to log "current visitor" information. Although the login process has verified that the user's user name and password are correct, but when the user jumps to other pages, the user information obtained from the login page is lost, which is not what the user would like to happen. At the same time, it is unrealistic to ask the user to enter a user name and password to authenticate to each page, which requires information to be shared between different pages.
in general, for PHP and other Web programming languages, you can use a cookie or a session to solve this problem. A
cookie is a small file that is stored on the client, and it is possible to store some information that needs to be shared between pages in this file. However, there are 3 drawbacks to cookies: One is the size can not exceed 4KB (different browsers may be different), and the other is that users can disable cookies in the browser settings, and the third is that cookies are poorly documented on the client. The session is usually done by means of a cookie, which is also invalidated if the user disables the cookie,session. Unlike cookies, the Session simply puts the identity of a message through a cookie on the client and the actual information is stored on the server, so that the security can be greatly improved. Now there is another way to use the session without a cookie, the URL rewriting technique. This approach is to interact with the service as a parameter of the session's identity as a URL, with the benefit of not being restricted by the client's disabling of cookies, which is cumbersome to use. The
use of the session in PHP is straightforward. PHP provides an automatic global variable $_session for processing session. However, it is important to note that if you do not set the auto-start session in the PHP configuration file, you must call the Session_Start () function to start the session before using the session.
Open login.php again, adding the following code in bold to record the user information.

<?php......if ($rs && $rs->num_rows > 0) {//Use SESSION to save current user session_start (); $_session[' uid '] = $ username;//in the actual application can use the previously mentioned redirection function to go to the home page $errmsg = "Login successful!"; /update User login information $ip = $_server[' remote_addr ']; Get the client's Ip$sql = "UPDATE t_user SET f_logintimes = f_logintimes + 1,"; $sql. = "F_lasttime=now (), f_loginip= ' $ip '"; $sql. = "WHERE f_username= ' $username '"; $db->query ($sql);} ......? >

Do not abuse session,session the biggest role is to maintain state between pages. Many beginners in mastering the session technology, it is easy to use the session as a magic weapon to store data, in the session to put a lot of data. Because this data is not released until the session expires, it can be a huge burden to the server.

Determine if the user is logged in

Now that the previous section has completed the task of saving the user name to the session, it is easy to determine whether the user is logged in or not, and the code is as follows:

<?phpsession_start (); if (Empty ($_session[' uid ')) {echo "You are not logged in and cannot access the current page! "; exit;}?" >

By judging whether the UID in the automatic global change $_session is empty, you can tell if the user is logged in. If the user is not logged in, they are prompted to be unable to access the current page and to terminate the program's run (or use a redirect statement to direct the page to the login page).

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.