09/10/2018, 18:14

Tạo User Log in trong PHP ( tut )

1-We will want to create a mysql table. We will need field for the ID#, User Name, and User Password. Here is the schema of my table:

Code:
CREATE TABLE user (
ID smallint(3) NOT NULL auto_increment,
Name varchar(30) NOT NULL default ',
Password varchar(32) NOT NULL default ',
PRIMARY KEY (ID),
UNIQUE KEY Name (Name)
) TYPE=MyISAM;
2-Replace the variables with there correct values and save it as common.php. This file will be included in all the pages that need to connect to the database. This is the most important file in the script. Make sure you save it as .php file.

Code:
<?php 

$User = "YourUserName"; 
$Pass = "YourUserPassword"; 
$Host = "YourDatabaseHost"; 
$DB = "YourMySQL Database"; 
$Table = "TableThatHoldsTheUserInfo"; 

?>
2- Creat a register page. What goes on when the user registers? A script inserts the users Name and Password into the database. First off we will need to create the basic form to let them do so.

Code:
<!doctype html public "-//W3C//DTD HTML 4.0 //EN"> 
<html> 
<head> 
<title>Login Signup</title> 
</head> 
<body> 
<form action="register.php" method="POST"> 
What is your desired username? <input type="text" name="Name" size="20"><br> 
What is your password? <input type="password" value="password" name="Password"><br> 
<input type="submit" value="Create!"> 
</form> 
</body> 
</html>
You can layout the form how ever you want, but keep in mind that the Name and Password input fields need to be there. Once you have the form ready, save it as register.html Now we need to create the registration script. All it will do is insert the data from the form into the database and tell the user that they are now registered.

Code:
<?php 
/* Include the DB connection Parameters */ 
include("common.php"); 

/*Connect to the DB using the info in common.php*/ 
if(!($link_id = mysql_connect($Host, $User, $Pass))) die(mysql_erorr()); 
mysql_select_db($DB); 

/*Here is where the actual work is done. We add slashes to the username 
to prevent errors in the query.  Then we encrypt the password.  This password is NEVER decryptable.  Never, 
so users can have a sense of security.  We insert, and then we say they are registered.  The Period as joins the strings 
togther, so we can join the returns of fucntions to that string without creating a new variable foreach one.*/ 
$sql = "INSERT INTO " . $Table . " VALUES(', '" . addslashes($_POST['Name']) . "', '" . md5($_POST['Password']) . "')"; 
if(!($result = mysql_query($sql))) { 
    die(mysql_error()); 
} else { 
    /*You can redirect them instead of just giving them a link, to do this: 
    you would replace the code below with header("location: login.html"); 
    Be warned, you can't send headers after text is outputted, so if you wanted 
    to have the message, and have them be forwareded, you would have to put the function 
    ob_start() at the very first line of this file, and call ob_end_flush() at the very end.*/ 
    echo "Your user account has been created!<br>"; 
    echo "<a href=login.html>Continues</a> to the login page"; 
} 

?>
3- Creat a login page ( login.html ). When the users logs in, there password and username are matched against a database. Just like before we will need a form to get the information from the user. Just like before, you can layout the form in anyway as long as the Name and Password values are there.

Code:
<!doctype html public "-//W3C//DTD HTML 4.0 //EN">
<html>
<head>
<title>Title here!</title>
</head>
<body>
<form method="post" action="login.php">
Enter your User Name <input type="text" name="Name" size="20"><br>
Enter you Password <input type="password" name="Password" size="20"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
save this file as login.html

4- Next we will create the login page. It will match there name and password against the ones stored in the database.

Code:
<?php 
include("common.php"); 

if(!($link_id = mysql_connect($Host, $User, $Pass))) die(mysql_erorr()); 
mysql_select_db($DB); 

/*This is were the actual log in takes place.  We tell mysql to select the ID where the Name is exactly like the Name from the Form 
where is Password is exactly like the encryption values of the password from the form.*/ 
$sql = "SELECT ID FROM " . $Table . " WHERE Name='" . addslashes($_POST['Name']) . "' AND Password='" . md5($_POST['Password']) . "' LIMIT 1"; 
if(!($result = mysql_query($sql))) die(mysql_error()); 

/*This is were we check the result.  We check to see how many rows were in the result of the query. If there is 1 one row in the result, that means 
there is one username with the right information, so that would mean they are logged in.*/ 
if(mysql_num_rows($result) == 1) { 
    /*Here we set a cookie that tells if the user has logged in and set it to last for a day.  The cookie is used on the members page to check 
    If they cookie is there they can see the page, if not they can't.*/ 
   
    setcookie("LoggedIn, TRUE, time()+(3600 * 24)); 


    /*You could also do the header() here just like I explained before.*/ 
    echo "Continue to the <a href=members.php>Members</a> page."; 
} else { 
    echo "Login failure"; 
} 
?>
5- Create a page called members.php and put this code in it:

Code:
<?php 
/*If the cookie isset then they are logged in, else the scripts dies and says they are not logged in.*/ 
if(!isset($_COOKIE['LoggedIn'])) die("You are not logged in!"); 

/*Your content goes here.  If it is php, keep it above the ?>.  If it is HTML code, put below the ?> or you will get errors*/ 
?>
6- Now that you have the files written, you can open up register.htm and register and go login to make sure that it works. B) :good:
quỷ kiếm viết 20:31 ngày 09/10/2018
Mấy bài này thật là có ý nghĩa.
Mình xin góp một ý nhỏ đó là dùng hàm PASSWORD để mã hoá mật khẩu. việc mã hoá này đảm bảo sự an toàn rất là cao vì theo mình biết thì không có hàm dịch ngược mật khẩu.
Nếu có thể thì có thể dịch bài này ra tiếng việt để cho mọi người đọc dễ hiểu hơn.
COTTONBELLY viết 20:23 ngày 09/10/2018
hàm MD5 chứ bạn , PHP làm gì có hàm PASSWORD :-)
Deathly Smile viết 20:24 ngày 09/10/2018
test
Deathly Smile viết 20:26 ngày 09/10/2018
Lưu ý chút nhé:
Các bạn chú ý vào phần kiểm tra cookie
if(!isset($_COOKIE['LoggedIn']))
Cách dùng $_COOKIE chỉ có hiệu lực nếu server sử dụng phiên bản PHP 4.1.0 trở lên, nếu ko các bạn sẽ phải dùng $HTTP_COOKIE_VARS. THêm nữa, nếu bạn dùng PHP từ 4.1.x đến trước 4.2.0 thì có thể dùng luôn $cookiename, theo VD này thì là if(!isset($LoggedIn))
mapu2003 viết 20:18 ngày 09/10/2018
Tớ làm như bạn nói, nhưng nó báo lỗi sau:
Warning: Cannot modify header information - headers already sent by (output started at C:\www\www\cdcvn\admin\login.php:8) in C:\www\www\cdcvn\admin\login.php on line 25
Sua giup minh nghen !
Bài liên quan
0