- PHP 세션 로그인 구현
- PHP 세션 로그인 구조
- PHP 세션 사용법 및 로그인 구현
1 의견[ | ]
PHP 쿠키 로그인 구현과 거의 비슷하다. 세션으로 구현할 때 다른 점은 다음 2가지이다.
- 세션 변수 사용 전에
session_start()
를 써야 한다.[1] - 로그아웃시 세션 제거함수
session_destory()
를 사용할 수 있다.
회원정보 테이블은 다음과 같다. 다만 본문서에서는 세션 구현에 집중하기 위해 의도적으로 DB부분을 제외하고 간단히 배열에 기록하였다. (login_ok.php 참조)
m_id | m_pw | m_name |
---|---|---|
user1 | pw1 | 김일구 |
user2 | pw2 | 박이팔 |
user3 | pw3 | 최삼칠 |
예를 들어 아이디 user2, 패스워드 pw2를 입력하면 박이팔 사용자로 로그인될 것이다.
이거 쓰지마
2 login.php[ | ]
html
Copy
<!DOCTYPE html>
<meta charset="utf-8" />
<form method='post' action='login_ok.php'>
<table>
<tr>
<td>아이디</td>
<td><input type='text' name='user_id' tabindex='1'/></td>
<td rowspan='2'><input type='submit' tabindex='3' value='로그인' style='height:50px'/></td>
</tr>
<tr>
<td>비밀번호</td>
<td><input type='password' name='user_pw' tabindex='2'/></td>
</tr>
</table>
</form>
3 login_ok.php[ | ]
PHP
Copy
<?php
if(!isset($_POST['user_id']) || !isset($_POST['user_pw'])) exit;
$user_id = $_POST['user_id'];
$user_pw = $_POST['user_pw'];
$members = [
'user1'=>['pw'=>'pw1', 'name'=>'김일구'],
'user2'=>['pw'=>'pw2', 'name'=>'박이팔'],
'user3'=>['pw'=>'pw3', 'name'=>'최삼칠']
];
if(!isset($members[$user_id])) {
echo "<script>alert('아이디 또는 패스워드가 잘못되었습니다.');history.back();</script>";
exit;
}
if($members[$user_id]['pw'] != $user_pw) {
echo "<script>alert('아이디 또는 패스워드가 잘못되었습니다.');history.back();</script>";
exit;
}
session_start();
$_SESSION['user_id'] = $user_id;
$_SESSION['user_name'] = $members[$user_id]['name'];
?>
<meta http-equiv='refresh' content='0;url=main.php'>
4 logout.php[ | ]
PHP
Copy
<?php
session_start();
session_destroy();
?>
<meta http-equiv='refresh' content='0;url=main.php'>
- → 쿠키와는 달리 세션 제거 전용함수가 있다.
5 테스트[ | ]
- [로그인]을 클릭하여 로그인 페이지로 이동.
- 아이디와 패스워드를 아무거나 입력하여 로그인해본다.
- 아이디 user1, 패스워드 pw1 을 입력하여 테스트
6 같이 보기[ | ]
- PHP 쿠키 로그인 구현
- jQuery AJAX 로그인 구현
- 세션
- 로그인
- PHP Warning: session destroy(): Trying to destroy uninitialized session
- ↑ 또한
session_start();
을 수행하기 전에 echo 등으로 HTML 내용을 출력하는 것은 안된다는 제약이 있다.
편집자 Jmnote 210.125.212.16 219.241.56.203 1.224.144.63 Jmnote bot 180.224.79.19
로그인하시면 댓글을 쓸 수 있습니다.
PHP 파일 다운로드 구현 2 (한글 파일명 지원) ― …PHP에서 오라클 DB 사용 ― YoWuPHP 파일 업로드 구현 ― 일리단사오육칠PHP 파일 업로드 구현 ― JmnotePHP 파일 다운로드 구현 2 (한글 파일명 지원) ― AnmkstLib my.php ― 신정섭Lib my.php ― Jmnote로또번호 생성 ―Pinkcrimson