같은 하지만 다른
PHP 쿠키 및 세션에 대한 튜토리얼에 오신 것을 환영합니다. PHP를 다루고 있다면 쿠키와 세션이라는 두 가지 매우 유사한 메커니즘이 있음을 알게 될 것입니다. 간단히 말해서,이 두 가지는 관련이 있지만 다른 것을 말합니다.
그러나 이 쿠키와 세션은 어떻게 작동합니까? 왜 2 개의“일시 저장 영역”이 필요한가? 이것이 우리가 이 안내서에서 자세히 다루는 것입니다. 알아 보려면 계속 읽으십시오!
ⓘ이 튜토리얼을 시작할 때 모든 예제 소스 코드가 포함 된 zip 파일을 포함 시켰으므로 모든 내용을 복사하여 붙여 넣을 필요가 없습니다.
다운로드
먼저 약속 된 예제 소스 코드에 대한 다운로드 링크가 있습니다.
소스 코드 다운로드
소스 코드를 다운로드하려면 여기를 클릭하십시오. MIT 라이센스에 따라 릴리스되었으므로 그 위에 빌드하거나 자신의 프로젝트에서 자유롭게 사용하십시오.
빠른 시작
COOKIES
쿠키로 시작하겠습니다. 쿠키는 임시 데이터를 포함하기 위해 클라이언트 PC에 저장된 작은 파일입니다.
쿠키가 필요한 이유는 무엇입니까?
이미 알고 계신 것처럼 HTTP는 상태 비 저장 프로토콜입니다. 즉,“다운로드 및 잊어 버린”종류의 것이므로 누가 누구인지 추적하지 않습니다. 예를 들어, 사용자가 http://my-site.com/products/의 "제품"페이지에 액세스하는 경우 :
그렇습니다. HTTP는 실제로 그렇게 간단합니다. 요청한 웹 페이지를 전송하기 위해 몇 초 동안 만 연결됩니다. 그러나 여기에 문제가 발생합니다. HTTP는 누구를 식별하지 않으며 정보를 저장하지 않습니다. 그렇다면… 개인 취향이나 장바구니와 같은 임시 데이터를 저장하려면 어떻게 해야 합니까? 쿠키가 유용한 곳입니다.
간단한 쿠키 예제
<html> <head> <title> Basic Cookie Example </title> <style> /* DEFAULT THEME */ body { background: #ffe0bc; color: #333; } /* DARK RED THEME */ body.darkr { background: #872929; color: #fff; } /* DARK BLUE THEME */ body.darkb { background: #293d87; color: #fff; } </style> <script> function setTheme (selected) { document.cookie = "theme=" + selected; document.body.className = selected; } </script> </head> <body class="<?=$_COOKIE['theme']?>"> <div> <input type="button" value="Use Default Theme" onclick="setTheme('default')"/> <input type="button" value="Use Red Theme" onclick="setTheme('darkr')"/> <input type="button" value="Use Blue Theme" onclick="setTheme('darkb')"/> </div> <p> * The cookie will store your preferred theme. Once set, it will use that theme even when you reload the page. </p> </body> </html>
이 예는 쿠키를 사용하여 사용자 기본 설정을 기억하는 방법을 설명해야 합니다.
COOKIES IN JAVASCRIPT
<html> <head> <title> Basic Cookie JS Example </title> <script> window.addEventListener("load", function(){ // TO SET & CHANGE A COOKIE VALUE // Much like query strings we only need to assign a key=value pair into document.cookie document.cookie = "hello=world"; document.cookie = "doge=goodboy"; document.cookie = "foo=bar"; // GETTING THE COOKIE // The cookie will be returned in a flat string // I.E. hello=world; doge=goodboy; foo=bar console.log(document.cookie); // We need to manually "decode" it... var decookie = {}, dc = decodeURIComponent(document.cookie); dc = dc.split(';'); for (var val of dc) { val = val.split('='); decookie[val[0].trim()] = val[1]; } console.log(decookie); // OUTPUT HTML var display = document.getElementById("display"); for (var key in decookie) { var line = document.createElement("div"); line.innerHTML = "KEY: " + key + " | VALUE: " + decookie[key]; display.appendChild(line); } // DELETE COOKIE // For example, to delete "foo" // Kind of dumb, but we set the expiry to a date that has long past document.cookie = "foo=;expires=Thu, 01 Jan 1970 00:00:01 GMT;"; console.log(document.cookie); }); </script> </head> <body> <div id="display"></div> </body> </html>
COOKIES IN PHP
쿠키는 PHP에서도 조작 할 수 있습니다 –
// SET & CHANGE COOKIE VALUE // setcookie(NAME, VALUE, EXPIRY DATE) setcookie("cate", "evil"); // Note - Expiry is optional, in Unix Timestamp setcookie("pupper", "bork", time() + 86400); // DELETE COOKIE // Same dumb thing... Set a long past date setcookie("pupper", "bork", time() - 86400); // SHOW COOKIE print_r($_COOKIE);
내 쿠키에는 무엇이 있습니까?
쿠키에 무엇이 저장되어 있는지 궁금하십니까? Chrome을 사용하는 경우 개발자 콘솔 (바로 가기 키 F12)> 애플리케이션 탭 아래> 쿠키를 엽니 다. Firefox, Edge 및 Safari도 비슷한 기능을 가지고 있어야 합니다.
SESSIONS
앞에서 소개 한 내용을 기억한다면 세션은 "서버의 쿠키"입니다. PHP에서 세션이 필요한 이유는 무엇입니까? 보안. 쿠키는 언제든지 사용자가 수정할 수 있으며, 장바구니 나 거래 세부 정보와 같은 것은 클라이언트 측에 있지 않기를 바랍니다.
간단한 세션 예
// START SESSION // (A) This will create a unique session ID that is stored into the cookie in PHPSESSID // (B) A session file will be created on the server temp folder, sess_SESSIONID // (C) On repeat visits, the client will provide the session ID contained inside the cookie // (D) PHP will then look for the respective temporary file and restore the session data session_start(); // SET & MODIFY SESSION VARIABLES if (isset($_POST['name'])) { $_SESSION['name'] = $_POST['name']; } // REMOVE SESSION VARIABLE if (isset($_POST['forget'])) { unset($_SESSION['name']); } // SESSION ID // If you want, you can get the current session ID with // echo session_id(); <html> <head> <title> Basic Session Example </title> </head> <body> <p> Your SESSION ID is =session_id() </p> // IF THE NAME IS RECORDED IN THE SESSION if (isset($_SESSION['name'])) { <p> HELLO, 'name'] =$_SESSION[ </p> <form method="post"> <input type="hidden" name="forget" value="1"/> <input type="submit" value="Forget Me"/> </form> // NEW SESSION else { } <form method="post"> What is your name? <input type="text" name="name" required value="uvuvwevwe onyetenyevwe ugweuhem osas"/> <input type="submit" value="Set"/> </form> } </body> </html>
왜 세션?
소개와 마찬가지로 세션은 쿠키보다 안전합니다. 세션 변수는 PHP로만 변경할 수 있으며 사용자가 쉽게 엉망으로 만들 수는 없습니다. 이것이 세션을 사용하여 장바구니 나 사용자 로그인과 같은 물건을 저장하여 쉽게 악용되지 않도록 하는 이유입니다.
유용한 비트
이것이 이 프로젝트의 전부이며, 여기에 도움이 될만한 추가 정보에 대한 작은 섹션이 있습니다.
참조 및 링크
빠른 요약
Cookies | Sessions | |
Stored at | Client-side. | Server-side. |
Managed with | Javascript and PHP. | PHP. |
Security | Less secure, the user can access and change anytime. | More secure, stored on the server, cannot be easily manipulated. |
등록된 댓글이 없습니다.