peri hokiperihokiclarustologisticsrimashaop.compola taktis menang gates of olympus x1000 perihokipemain perihoki bongkar trik jepep starlight princess x1000perihoki beri panduan lengkap bermain mahjong ways 2 pgsofttips cara penghasil uang pgsoft mahjong ways 2 perihokimahjong wins 3 perihoki memberikan penggali terbesarfenomena gates of olympus buka peluang besar bagi duta76cara dapat pola emas rahasia di duta7 wild west goldtrik menang pgsoft mahjong ways 2 modal receh maxwin duta76duta76 main pgsoft mahjong ways 2 di sela istirahatscatter hitam mahjong wins 3 spin pasti jepe duta76pola petir tersembunyi gates of olympus perihokipgsoft perkuat mahjong ways 2 di akun perihokiperihoki beri pola jitu mahjong wins 3 auto maxwin5 scatter jackpot driver ojolstrategi satpam scatter mahjongstrategi menang mahjong abc1131scatter emas pabrik wonosobomodal tipis scatter jadi cuanrtp mahjong ways supir menanginsting kuat bermain mahjong waysmengungkap keunggulan mahjong waysserunya mahjong bermodal kecil untung melimpahstrategi terbaik untuk menang mahjongterus main terus gacormenang banyak dengan scatter mahjong ways1menggali kehebatan mahjong winsrahasia nurul di mahjong waysstrategi mahjong yang mengubah permainan andateknik menang mahjong ways yang efektif

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 282

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_set_cookie_params(): Cannot change session cookie parameters when headers already sent

Filename: Session/Session.php

Line Number: 294

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 304

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 314

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 315

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 316

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 317

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 375

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: drivers/Session_files_driver.php

Line Number: 108

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_set_save_handler(): Cannot change save handler when headers already sent

Filename: Session/Session.php

Line Number: 110

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_start(): Cannot start session when headers already sent

Filename: Session/Session.php

Line Number: 143

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

Session và cookie trong php - Freetuts
LÝ THUYẾT
XỬ LÝ FORM
BÀI TẬP
CÁC CHỦ ĐỀ
BÀI MỚI NHẤT
MỚI CẬP NHẬT

Bài 25: Session và cookie trong php

Session và Cookie dùng để lưu trữ dữ liệu tạm thời và từ đó hệ thống có thể đưa ra những quyết định về quyền hạn hoặc là những tùy chọn riêng tư. Cả hai tuy có chung chức năng là lưu trữ dữ liệu nhưng bên trong nó lại khác nhau. Session dùng để lưu trữ dữ liệu trên Server và đồng thời nó sẽ có một đoạn code dữ liệu được lưu trữ ở client (cookie). Còn Cookie thì lưu trữ dữ liệu trên máy Client. Để hiểu rõ hơn thì ta phải vào tìm hiểu cụ thể.

test php

banquyen png
Bài viết này được đăng tại freetuts.net, không được copy dưới mọi hình thức.

1. Session trong PHP

Biến Session trong PHP được dùng để lưu trữ thông tin của người dùng hoặc là lưu trữ tùy chọn cấu hình hệ thống cho người dùng. Đặc biệt mỗi client sẽ có một ID session khác nhau nên việc thông tin Session ở Client A bị ảnh hưởng qua Client B là điều không thể. Thông thường chúng ta sử dụng Session để lưu thông tin đăng nhập, giỏ hàng hoặc những dữ liệu mang tính chất tạm thời và mỗi client sẽ có dư liệu khác nhau.

Đăng ký session

Trước khi bạn sử dụng session bạn phải khai báo cho PHP biết bằng cách đặt dòng lệnh session_start() phía trên đầu mỗi file. Nếu bạn dùng nhiều file include lẫn nhau thì đặt nó ở file chính.

Ví dụ:

Bài viết này được đăng tại [free tuts .net]

 

<?php session_start(); ?>
 
<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <div>TODO write content</div>
    </body>
</html>

 

Dòng lệnh session_start() sẽ đăng ký phiên làm việc của người dùng trên Server, từ đó Server sẽ tạo ra một ID riêng không trùng lặp để nhận diện cho client hiện tại. Dòng này bắt buộc có.

Lưu trữ session

Tất cả Session được lưu trữ trong biến toàn cục $_SESSION, vì thể để lưu thêm dữ liệu Session hay là thay đổi dữ liệu của Session thì ta sẽ thao tác trên biến đó. Lưu ý với bạn trước khi dùng phép lấy giá trị Session bạn phải kiểm tra sesion đó có tồn tại không rồi hãy lấy.

Để lưu một giá trị mới vào Session ta dùng cú pháp như sau: $_SESSION['session_name'] = $session_value

Để lấy giá trị Session ta dùng cú pháp sau: $tenbien = $_SESSION['session_name']. Như tôi đề cập ở trên trước khi bạn lấy giá trị Session bạn nên kiểm tra nó có tồn tại không rồi hãy lấy.

Ví dụ:

Bạn tạo một file session.php và copy nội dung này vào:

 

<?php session_start();
// Nếu click vào nút Lưu Session
if (isset($_POST['save-session']))
{
    // Lưu Session
    $_SESSION['name'] = $_POST['username'];
}
?>
<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <h1>
            <?php
            // Hiển thị thông tin lưu trong Session
            // phải kiểm tra có tồn tại không trước khi hiển thị nó ra
            if (isset($_SESSION['name']))
            {
                echo 'Tên Đăng Nhập Là: ' . $_SESSION['name'];
            }
            ?>
        </h1>
        <form method="POST" action="">
            <input type="text" name="username" value=""/> <br/>
            <input type="submit" name="save-session" value="Lưu Session"/>
        </form>
    </body>
</html>

 

Bạn hãy nhập tên vào sau đó nhấn vào button Lưu Sessoin. sau đó bạn refresh lại trang bạn sẽ thấy thông tin bạn đã được lưu trữ trên Server nên có hiển thị ra.

Xóa session

Tất cả các giá trị Session đều lưu trữ trong biến $_SESSION nên để xóa nó các bạn chỉ việc dùng hàm unset($_SESSION['session_name']), trong đó hàm unset dùng để giải phóng một biến ra khỏi bộ nhớ.

Nếu bạn muốn xóa hết tất cả các Session thì ta dùng hàm session_destroy().

Ví dụ:

 

// Xóa session name
unset($_SESSION['name']);
 
// Xóa hết session
session_destroy();

 

Còn rất nhiều hàm khác các bạn tham khảo tại đây.

2. Cookie trong PHP

Cookie thường được dùng để lưu trữ các tùy chọn riêng của trang web từng user, nó là một file nhỏ được Server chỉ định lưu trữ trên máy tính của Client và PHP có thể truy xuất tới được. Và để sử dụng được Cookie thì trình duyệt phải hỗ trợ chức năng này, nếu không thì Cookie trở nên vô dụng.

Cookie sẽ không bị mất khi bạn đóng ứng dụng, nó phụ thuộc vào thời gian sống mà bạn thiết lập cho nó. Ví dụ bạn thiết lập Cookie lưu trữ thông tin đăng nhập trong vòng 15 phút thì sau 15 phút mà bạn không có một thao tác thay đổi trên nó thì Cookie của bạn sẽ bị chết. Đây chính là sự lợi hại của việc sư dụng Cookie.

Lưu trữ Cookie

Để lưu trữ Cookie ta dùng cú pháp sau và phải đặt trước thẻ html: setcookie($name, $value, $expire, $path, $domain).

Trong đó:

  • $name: là tên của Cookie
  • $value: giá trị của Cookie
  • $expire: thời gian sống của Cookie
  • $path : đường dẫn lưu trữ Cookie
  • $domain: tên của domain

Ví dụ: lưu trữ tên đăng nhập username = ‘thehalfheart’ trong một giờ

 

<!DOCTYPE html>
 
<?php
    setcookie('username', 'thehalfheart', time() + 3600);
?>
 
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
    </body>
</html>

 

Lấy giá trị Cookie

Tất cả Cookie được lưu trữ trong biến toàn cục $_COOKIE nên để lấy giá trị Cookie ta dùng cú pháp sau: $bien = $_COOKIE['cookie_name']. Cũng như lưu ý ở phần Session bạn nên kiểm tra có tồn tại Cookie không trước khi lấy nhé, nếu không sẽ bị thông báo lỗi nếu nó không tồn tại.

Ví dụ: Lấy giá tri username vừa lưu trữ ở trên

 

if (isset($_COOKIE['username']))
{
echo $_COOKIE['username'];
}

 

Xóa Cookie

Để xóa Cookie bạn chỉ việc thiết lập thời gian sống của nó sang quá trị âm nhiều hơn hoặc bằng giá trị sống lúc bạn thiết lập.

Ví dụ: xóa Cookie đã thiết lập ở trên

 

setcookie("username", "", time()-3600);

 

Lời Kết

Bài này chúng ta đã nghiên cứu được 2 cách lưu trữ dữ liệu tạm thời của người dùng đó là Session và Cookie. Những ví dụ trên rất căn bản nhưng thực tết rất hay sử dụng, nếu các bạn muốn tìm hiểu sâu hơn thì lên PHP.NET để tìm hiểu. Nhưng mình nghĩ các bạn hiện tại chưa rành nhiều nên chỉ cần biết bấy nhiêu đó là đủ.

Cùng chuyên mục:

Hàm key_exists() trong PHP

Hàm key_exists() trong PHP

Cách sử dụng key_exists() trong PHP

Hàm mysqli_fetch_row() trong PHP

Hàm mysqli_fetch_row() trong PHP

Cách sử dụng mysqli_fetch_row() trong PHP

Hàm end() trong PHP

Hàm end() trong PHP

Cách sử dụng end() trong PHP

Hàm mysqli_field_count() trong PHP

Hàm mysqli_field_count() trong PHP

Cách sử dụng mysqli_field_count() trong PHP

Hàm count() trong PHP

Hàm count() trong PHP

Cách sử dụng count() trong PHP

Hàm mysqli_field_seek() trong PHP

Hàm mysqli_field_seek() trong PHP

Cách sử dụng mysqli_field_seek() trong PHP

Hàm compact() trong PHP

Hàm compact() trong PHP

Cách sử dụng compact() trong PHP

Hàm mysqli_field_tell() trong PHP

Hàm mysqli_field_tell() trong PHP

Cách sử dụng mysqli_field_tell() trong PHP

Hàm array_values() trong PHP

Hàm array_values() trong PHP

Cách sử dụng array_values() trong PHP

Hàm mysqli_free_result() trong PHP

Hàm mysqli_free_result() trong PHP

Cách sử dụng mysqli_free_result() trong PHP

Hàm array_unshift() trong PHP

Hàm array_unshift() trong PHP

Cách sử dụng array_unshift() trong PHP

Hàm mysqli_get_charset() trong PHP

Hàm mysqli_get_charset() trong PHP

Cách sử dụng mysqli_get_charset() trong PHP

Hàm array_shift() trong PHP

Hàm array_shift() trong PHP

Cách sử dụng array_shift() trong PHP

Hàm mysqli_get_client_stats() trong PHP

Hàm mysqli_get_client_stats() trong PHP

Cách sử dụng mysqli_get_client_stats() trong PHP

Hàm array_unique() trong PHP

Hàm array_unique() trong PHP

Cách sử dụng array_unique() trong PHP

Hàm mysqli_get_client_version() trong PHP

Hàm mysqli_get_client_version() trong PHP

Cách sử dụng mysqli_get_client_version() trong PHP

Hàm array_uintesect() trong PHP

Hàm array_uintesect() trong PHP

Cách sử dụng array_uintesect() trong PHP

Hàm mysqli_get_connection_stats() trong PHP

Hàm mysqli_get_connection_stats() trong PHP

Cách sử dụng mysqli_get_connection_stats() trong PHP

Hàm array_sum() trong PHP

Hàm array_sum() trong PHP

Cách sử dụng array_sum() trong PHP

Hàm mysqli_get_host_info() trong PHP

Hàm mysqli_get_host_info() trong PHP

Cách sử dụng mysqli_get_host_info() trong PHP

Top