Está en la página 1de 12

Overview In this tutorial create 3 files 1. main_login.php 2. checklogin.php 3. login_success.php Step 1. Create 2. Create 3. Create 4. Create 5.

Create

table "members" in database "test". file main_login.php. file checklogin.php. file login_success.php. file logout.php

If you don't know how to create databse, click here

Create table "members"

CREATE TABLE `members` ( `id` int(4) NOT NULL auto_increment, `username` varchar(65) NOT NULL default '', `password` varchar(65) NOT NULL default '', PRIMARY KEY (`id`) ) TYPE=MyISAM AUTO_INCREMENT=2 ; --- Dumping data for table `members` -INSERT INTO `members` VALUES (1, 'john', '1234');

Create file main_login.php View In Browser

############### Code <table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC"> <tr> <form name="form1" method="post" action="checklogin.php"> <td> <table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF"> <tr> <td colspan="3"><strong>Member Login </strong></td> </tr> <tr> <td width="78">Username</td> <td width="6">:</td> <td width="294"><input name="myusername" type="text" id="myusername"></td> </tr> <tr> <td>Password</td> <td>:</td> <td><input name="mypassword" type="text" id="mypassword"></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td><input type="submit" name="Submit" value="Login"></td> </tr> </table> </td> </form> </tr> </table>

Create file checklogin.php

############### Code <?php $host="localhost"; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name="test"; // Database name

$tbl_name="members"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // username and password sent from form $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Register $myusername, $mypassword and redirect to file "login_success.php" session_register("myusername"); session_register("mypassword"); header("location:login_success.php"); } else { echo "Wrong Username or Password"; } ?>

Create file login_success.php

############### Code // Check if session is not registered , redirect back to main page. // Put this code in first line of web page. <? session_start(); if(!session_is_registered(myusername)){ header("location:main_login.php"); } ?> <html> <body> Login Successful </body> </html>

Logout.php

If you want to logout, create this file // Put this code in first line of web page. <? session_start(); session_destroy(); ?>

For PHP5 User - checklogin.php

############### Code <?php ob_start(); $host="localhost"; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name="test"; // Database name $tbl_name="members"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // Define $myusername and $mypassword $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Register $myusername, $mypassword and redirect to file "login_success.php" session_register("myusername"); session_register("mypassword"); header("location:login_success.php"); } else {

echo "Wrong Username or Password"; } ob_end_flush(); ?>

Encrypting Password - Make your Login More Secure

We are going to create a simple login system using PHP code on our pages, and a MySQL database to store our users information. We will track the users who are logged in withcookies. Before we can create a login script, we first need to create a database to store users. For the purpose of this tutorial we will simply need the fields "username" and "password", however you can create as many fields as you wish. CREATE TABLE users (ID MEDIUMINT NOT NULL AUTO_INCREMENT PRIMARY KEY, username VARCHAR(60), password VARCHAR(60)) This will create a database called users with 3 fields: ID, username, and password. <?php // Connects to your Database mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()); mysql_select_db("Database_Name") or die(mysql_error()); //This code runs if the form has been submitted if (isset($_POST['submit'])) {

//This makes sure they did not leave any fields blank if (!$_POST['username'] | !$_POST['pass'] | !$_POST['pass2'] ) {

die('You did not complete all of the required fields'); }

// checks if the username is in use if (!get_magic_quotes_gpc()) { $_POST['username'] = addslashes($_POST['username']); } $usercheck = $_POST['username']; $check = mysql_query("SELECT username FROM users WHERE username = '$usercheck'") or die(mysql_error()); $check2 = mysql_num_rows($check);

//if the name exists it gives an error if ($check2 != 0) { die('Sorry, the username '.$_POST['username'].' is already in use.'); } // this makes sure both passwords entered match if ($_POST['pass'] != $_POST['pass2']) { die('Your passwords did not match. '); }

// here we encrypt the password and add slashes if needed $_POST['pass'] = md5($_POST['pass']); if (!get_magic_quotes_gpc()) { $_POST['pass'] = addslashes($_POST['pass']); $_POST['username'] = addslashes($_POST['username']); }

// now we insert it into the database $insert = "INSERT INTO users (username, password)

VALUES ('".$_POST['username']."', '".$_POST['pass']."')"; $add_member = mysql_query($insert); ?>

<h1>Registered</h1> <p>Thank you, you have registered - you may now login</a>.</p>

<?php } else { ?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <table border="0"> <tr><td>Username:</td><td> <input type="text" name="username" maxlength="60"> </td></tr> <tr><td>Password:</td><td> <input type="password" name="pass" maxlength="10"> </td></tr> <tr><td>Confirm Password:</td><td> <input type="password" name="pass2" maxlength="10"> </td></tr> <tr><th colspan=2><input type="submit" name="submit" value="Register"></th></tr> </table> </form> <?php } ?> Registration Full Code Basically what this does is check to see if the form has been submitted. If it has been submitted it checks to make sure that the data is all OK (passwords match, username isn't in use) as documented in the code. If everything is OK it adds the user to the database, if not it returns the appropriate error.

If the form has not been submitted, they are shown the registration form, which collects the username and password. <?php // Connects to your Database mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()); mysql_select_db("Database_Name") or die(mysql_error()); //Checks if there is a login cookie if(isset($_COOKIE['ID_my_site'])) //if there is, it logs you in and directes you to the members page { $username = $_COOKIE['ID_my_site']; $pass = $_COOKIE['Key_my_site']; $check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error()); while($info = mysql_fetch_array( $check )) { if ($pass != $info['password']) { } else { header("Location: members.php");

} } } //if the login form is submitted if (isset($_POST['submit'])) { // if form has been submitted

// makes sure they filled it in if(!$_POST['username'] | !$_POST['pass']) {

die('You did not fill in a required field.'); } // checks it against the database

if (!get_magic_quotes_gpc()) { $_POST['email'] = addslashes($_POST['email']); } $check = mysql_query("SELECT * FROM users WHERE username = '".$_POST['username']."'")or die(mysql_error());

//Gives error if user dosen't exist $check2 = mysql_num_rows($check); if ($check2 == 0) { die('That user does not exist in our database. <a href=add.php>Click Here to Register</a>'); } while($info = mysql_fetch_array( $check )) { $_POST['pass'] = stripslashes($_POST['pass']); $info['password'] = stripslashes($info['password']); $_POST['pass'] = md5($_POST['pass']);

//gives error if the password is wrong if ($_POST['pass'] != $info['password']) { die('Incorrect password, please try again.'); } Script continued and explained on the next page. else { // if login is ok then we add a cookie $_POST['username'] = stripslashes($_POST['username']);

$hour = time() + 3600; setcookie(ID_my_site, $_POST['username'], $hour); setcookie(Key_my_site, $_POST['pass'], $hour);

//then redirect them to the members area header("Location: members.php"); } } } else {

// if they are not logged in ?> <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> <table border="0"> <tr><td colspan=2><h1>Login</h1></td></tr> <tr><td>Username:</td><td> <input type="text" name="username" maxlength="40"> </td></tr> <tr><td>Password:</td><td> <input type="password" name="pass" maxlength="50"> </td></tr> <tr><td colspan="2" align="right"> <input type="submit" name="submit" value="Login"> </td></tr> </table> </form> <?php }

?> Login Full Code This script first checks to see if the login information is contained in a cookie on the users computer. If it is, it tries to log them in. If this is successful they are redirected to the members area. If there is no cookie, it allows them to login. If the form has been submitted, it checks it against the database and if it was successful sets a cookie and takes them to the members area. If it has not been submitted, it shows them the login form. <?php // Connects to your Database mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()); mysql_select_db("Database_Name") or die(mysql_error()); //checks cookies to make sure they are logged in if(isset($_COOKIE['ID_my_site'])) { $username = $_COOKIE['ID_my_site']; $pass = $_COOKIE['Key_my_site']; $check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error()); while($info = mysql_fetch_array( $check )) {

//if the cookie has the wrong password, they are taken to the login page if ($pass != $info['password']) { } header("Location: login.php");

//otherwise they are shown the admin area else { echo "Admin Area<p>"; echo "Your Content<p>"; echo "<a href=logout.php>Logout</a>"; } }

} else

//if the cookie does not exist, they are taken to the login screen { header("Location: login.php"); } ?> This code checks our cookies to make sure the user is logged in, the same way the login page did. If they are logged in, they are shown the members area. If they are not logged in they are redirected to the login page.

Logout Page
<?php $past = time() - 100; //this makes the time in the past to destroy the cookie setcookie(ID_my_site, gone, $past); setcookie(Key_my_site, gone, $past); header("Location: login.php"); ?> All our logout page does is destroy the cookie, and then direct them back to the login page. We destroy the cookie by setting the expiration to some time in the past.

También podría gustarte