Hướng dẫn học : Viết ứng dụng đăng nhập với CakePHP

Hướng dẫn học : Viết ứng dụng đăng nhập với CakePHP

1.Giới thiệu:

Trong bài viết này , tôi sẽ hướng dẫn các bạn cách áp dụng Session để viết 1 ứng dụng khá quen thuộc đó là chức năng đăng nhập .
Qua bài Tutorial này các bạn sẽ có được kiến thức gì :
- Cách vận dụng các hàm xử lý Session thông dụng
- Cách sử dụng layout với file CSS được thiết kế riêng theo ý muốn
- Cách load 1 file view theo ý muốn , không tuân theo qui tắc load file view của CakePHP
- Cách sử dụng hàm của Model từ Controller tương ứng

Hướng dẫn học :  Viết ứng dụng đăng nhập với CakePHP

Chuẩn bị CSDL :

CREATE TABLE `users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL,
  `password` varchar(20) NOT NULL,
  `email` varchar(50) DEFAULT NULL,
  `gender` int(1) DEFAULT NULL,
  PRIMARY KEY (`user_id`)
);
-- ----------------------------
-- Records 
-- ----------------------------
INSERT INTO `users` VALUES ('1', 'admin', 'admin', '[email protected]', '1');
INSERT INTO `users` VALUES ('2', 'user', 'user', '[email protected]', '2');
INSERT INTO `users` VALUES ('3', 'assistant', 'assistant', '[email protected]', '1');
INSERT INTO `users` VALUES ('4', 'kenny', 'kenny', '[email protected]', '1');

2.Yêu cầu :

Tạo trang hiển hiển thị thông tin user . Khi truy cập vào trang này ,người sử dụng phải đăng nhập username và password hợp lệ. Nếu không , khi truy cập vào trang này , thì người sử sẽ tự động được chuyển ra trang đăng nhập.

3.Các thành phần chính trong ứng dụng :

- Controller User (app/controllers/users_controller.php)
giữ vai trò là controller chính, gồm các function :
o View() : hiển thị thông tin khi đăng nhập thành công
o Login() : Kiểm tra username và password trước khi đăng nhập
o Logout() : Thoát khỏi trang View (hủy Session)
- Model User (app/models/user.php)
giữ vai trò kết nối bảng users trong CSDL, gồm các function :
o CheckLogin() : kiểm tra username và password trong CSDL khi người dùng đăng nhập
- View User (app/views/demos/users)
o login.ctp : trang Login
o index.ctp : trang hiển thị thông tin khi đăng nhập thành công
- File CSS
o webroot/css/login.css

4.Bắt đầu viết ứng dụng :

Controller User (app/controllers/users_controller.php)

<?php
class UsersController extends AppController{
    var $layout = false; // Không sử dụng Layout mặc định của CakePHP , dùng file CSS riêng
    var $name = "Users";
    var $helpers = array("Html");
    var $component = array("Session");     
    var $_sessionUsername  = "Username"; // tên Session được qui định trước
    
    
    //---------- View
    function view(){
        if(!$this->Session->read($this->_sessionUsername)) // đọc Session xem có tồn tại không
            $this->redirect("login");
        else
            $this->render("/demos/users/index"); // load 1 file view index.ctp trong thư mục “views/demos/users”/
    }
    
    //--------- Login
    function login(){
      $error="";// thong bao loi
        if($this->Session->read($this->_sessionUsername))
            $this->redirect("view");

        if(isset($_POST['ok'])){
           $username = $_POST['username'];
           $password = $_POST['password']; 
           if($this->User->checkLogin($username,$password)){
                $this->Session->write($this->_sessionUsername,$username);
                $this->redirect("view");
            }else{
                $error = "Username or Password wrong";
           }
        }
        $this->set("error",$error);
        $this->render("/demos/users/login");
    }
    //---------- Logout
    function logout(){
        $this->Session->delete($this->_sessionUsername);
        $this->redirect("login");
    }
}

Model User (app/models/user.php)

<?php
class User extends AppModel{
    var $name = "User";
    
    function checkLogin($username,$password){
        $sql = "Select username,password from users Where username='$username' AND password ='$password'";
        $this->query($sql);
        if($this->getNumRows()==0){
            return false;
        }else{
            return true;
        }
    }
}
?>

Các file View :
index.ctp (app/views/demos/users/index.ctp)

<html>
<title>Home Page</title>
<body>
<span>Login : <?php echo $this->Session->read("Username");?> | <a href="logout">Logout</a></span>
<h1>Wellcome to CakePHP Framework</h1>
</body>
</html>

login.ctp (app/views/demos/users/login.ctp)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php echo $this->Html->css("login"); //load file CSS riêng (app/webroot/css/login.css)?>
<title>Login</title>
<body>
    <form method="post" action="">
        <fieldset>
        <legend>Login</legend>
        <label>Username</label><input type="text" name="username" size="20" /><br />
        <label>Password</label><input type="password" name="password" size="20" /><br />
        <label>&nbsp;</label><input type="submit" name="ok" value="Login" />
       <!—Hiển  thị thông báo lỗi nếu có-->
        <span class="error"><?php echo $error; ?></span>
        </fieldset>
    </form>
</body>
</html>

login.css (app/webroot/css/login.css)

@charset "utf-8";
body {
    background-color: #FFF;
    font-family: Tahoma;
    color: #2c2c2c;
    font-size: 12px;
    font-weight: bold;
}

label{
    float:left;
    width:100px;
    margin-top:3px;
    text-align:center;
}
input {
    margin-bottom:3px;
    border: 1px solid #2c2c2c;
}

legend{
    font-weight:900;
    color:#2c2c2c;
}

fieldset{
    width:300px;
    border:1px solid #2c2c2c;
    margin-top: 100px;
    margin-right: auto;
    margin-bottom: auto;
    margin-left: auto;
    background-color: #ff9900;
}
.button {
}
.error {
    font-family: Verdana, Geneva, sans-serif;
    font-size: 12px;
    color: #FFF;
} 

Chạy thử ứng dụng : http://localhost/cakephp/users/login

Đăng nhập thành công

Tags: 
Bạn thấy bài viết này như thế nào?: 
No votes yet
Ảnh của Khanh Hoang

Khanh Hoang - Kenn

Kenn is a user experience designer and front end developer who enjoys creating beautiful and usable web and mobile experiences.

Advertisement

 

jobsora

Dich vu khu trung tphcm

Dich vu diet chuot tphcm

Dich vu diet con trung

Quảng Cáo Bài Viết

 
Phần 1: Giới thiệu sơ lược, cơ bản WordPress

Phần 1: Giới thiệu sơ lược, cơ bản WordPress

Nếu bạn đã sẵn sàng rồi thì hãy để mình đưa bạn vào tham quan trước về các khái niệm quan trọng về WordPress cũng như những lý do rất tuyệt vời để bạn nên sử dụng nó ngay từ hôm nay.

Công cụ soát lỗi trên máy Mac

Công cụ soát lỗi trên máy Mac

Bất kể hệ điều hành Mac OS X trên máy tính của bạn có đang như thế nào, chỉ cần phần cứng của nó trục trặc, bạn sẽ ngay lập tức được chứng kiến vô số các biểu hiện chẳng tốt đẹp gì.

Bộ phần mềm máy chủ tổng hợp: eBox

Bộ phần mềm máy chủ tổng hợp: eBox

Như đã nói trong một số post trước, phần mềm máy chủ là lĩnh vực mà PMNM phổ biến nhất, hiệu quả nhất từ trước khi Windows NT, Exchange, … ra đời.

Công ty diệt chuột T&C

 

Diet con trung