Advertisement
  1. Code
  2. PHP

새 회원 이메일 검증 구현법

Scroll to top
Read Time: 16 min

() translation by (you can also view the original English article)

웹사이트에서 계정을 생성하고 회사에서 보낸 이메일 확인을 요구받고 검증 링크를 클릭하여 활성 한적이 있나요? 스팸 메일 계정 수를 줄일 수 있는 고도의 방법입니다. 이 단원에서 그런 일을 수행하는 유용한 방법을 배울 것입니다!


빌드하려는것은?

훌륭한 PHP 가입 스크립트를 빌드할건데 사용자가 접근 권한을 얻기 위해 웹사이트의 "회원 영역"에서 계정을 생성할 수 있도록 하려 합니다.
사용자 자신의 계정을 만든 후, 계정은 다음 경우까지 잠겨있을 것입니다. 사용자가 그의 이메일 받은 편지함에 받게 될 검증용 링크를 클릭할 때까지.


단계 1 - 가입 페이지

처음 필요되는것은 방문자들이 계정을 가입할 수 있는 간단한 페이지 여서 그것을 먼저 만들어보겠습니다.
PHP 학습임을 상기시켜드리고 싶고 개인 의견상 PHP 이전에 HTML의 기본을 알아야 한다고 생각합니다. HTML과 CSS 각 줄마다 코멘트들을 추가하여 설명할 것입니다.

index.php - 기본 폼을 지닌 가입 페이지

1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2
3
<html xmlns="http://www.w3.org/1999/xhtml">
4
<head>
5
  <title>NETTUTS > Sign up</title>
6
	<link href="css/style.css" type="text/css" rel="stylesheet" />
7
</head>
8
<body>
9
	<!-- start header div -->	
10
	<div id="header">
11
		<h3>NETTUTS > Sign up</h3>
12
	</div>
13
	<!-- end header div -->	
14
	
15
	<!-- start wrap div -->	
16
	<div id="wrap">
17
		
18
		<!-- start php code -->
19
		
20
		<!-- stop php code -->
21
	
22
		<!-- title and description -->	
23
		<h3>Signup Form</h3>
24
		<p>Please enter your name and email addres to create your account</p>
25
		
26
		<!-- start sign up form -->	
27
		<form action="" method="post">
28
			<label for="name">Name:</label>
29
			<input type="text" name="name" value="" />
30
			<label for="email">Email:</label>
31
			<input type="text" name="email" value="" />
32
			
33
			<input type="submit" class="submit_button" value="Sign up" />
34
		</form>
35
		<!-- end sign up form -->	
36
		
37
	</div>
38
	<!-- end wrap div -->	
39
</body>
40
</html>

css/style.css - index.php와 다른 페이지들의 스타일시트.

1
/* Global Styles */
2
3
*{
4
	padding: 0; /* Reset all padding to 0 */
5
	margin: 0; /* Reset all margin to 0 */
6
}
7
8
body{
9
	background: #F9F9F9; /* Set HTML background color */
10
	font: 14px "Lucida Grande";  /* Set global font size & family */
11
	color: #464646; /* Set global text color */
12
}
13
14
p{
15
	margin: 10px 0px 10px 0px; /* Add some padding to the top and bottom of the <p> tags */
16
}
17
18
/* Header */
19
20
#header{
21
	height: 45px; /* Set header height */
22
	background: #464646; /* Set header background color */
23
}
24
25
#header h3{
26
	color: #FFFFF3; /* Set header heading(top left title ) color */
27
	padding: 10px; /* Set padding, to center it within the header */
28
	font-weight: normal; /* Set font weight to normal, default it was set to bold */
29
}
30
31
/* Wrap */
32
33
#wrap{
34
	background: #FFFFFF; /* Set content background to white */
35
	width: 615px; /* Set the width of our content area */
36
	margin: 0 auto; /* Center our content in our browser */
37
	margin-top: 50px; /* Margin top to make some space between the header and the content */
38
	padding: 10px; /* Padding to make some more space for our text */
39
	border: 1px solid #DFDFDF; /* Small border for the finishing touch */
40
	text-align: center; /* Center our content text */
41
}
42
43
#wrap h3{
44
	font: italic 22px Georgia; /* Set font for our heading 2 that will be displayed in our wrap */
45
}
46
47
/* Form & Input field styles */ 
48
49
form{
50
	margin-top: 10px; /* Make some more distance away from the description text */
51
}
52
53
form .submit_button{
54
	background: #F9F9F9; /* Set button background */
55
	border: 1px solid #DFDFDF; /* Small border around our submit button */
56
	padding: 8px; /* Add some more space around our button text */
57
}
58
59
input{
60
	font: normal 16px Georgia; /* Set font for our input fields */
61
	border: 1px solid #DFDFDF; /* Small border around our input field */
62
	padding: 8px; /* Add some more space around our text */
63
}

보다시피, 각 줄에 그들이 무엇을 하는지 설명하는 코멘트를 추가했습니다. 또한, index.php 파일에서 다음과 같은 코멘트를 발견 할 수도 있습니다.

1
<!-- start php code -->
2
3
<!-- stop php code -->

이 2줄 사이체 PHP 코드를 써넣을 것입니다!


단계 2 - 입력 검증

첫째는 우리가 정보를 검증하는 코드 조각을 만드는 것 입니다. 마쳐야할 짧은 목록 항목들이 있습니다.

  • name 필드가 비어있지 않은지.
  • name 이 짧지 않은지.
  • email 필드가 비어있지 않은지.
  • email 주소가 유효한 xxx@xxx.com 인지.

첫 단계는 폼이 전송시 검사하는것이고 필드들은 비어 있지 않아야 합니다.

1
<!-- start PHP code -->
2
<?php
3
4
	if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['email']) && !empty($_POST['email'])){
5
		// Form Submited

6
	}
7
	    	
8
?>
9
<!-- stop PHP Code -->

분석 시간! 시작은 IF 문을 사용하고 첫 유효성 검사는 이름 필드:

1
	if(  ){ // If statement is true run code between brackets

2
	
3
	}
4
	
5
	isset($_POST['name']) // Is the name field being posted; it does not matter whether it's empty or filled.

6
	&& // This is the same as the AND in our statement; it allows you to check multiple statements.

7
	!empty($_POST['name']) // Verify if the field name is not empty

8
	
9
	isset($_POST['email']) // Is the email field being posted; it does not matter if it's empty or filled.

10
	&& // This is the same as the AND in our statement; it allows you to check multiple statements.

11
	!empty($_POST['email']) // Verify if the field email is not empty

필드를 공백으로 두고 폼을 전송하려 하면 아무것도 일어나지 않을 것입니다. 양쪽 필드들을 모두 채웠다면 스크립트는 대괄호 사이의 코드를 실행할 것입니다.
이메일 주소가 올바른지 검사하는 코드 조각을 만들 것입니다. 값이 올바르지 않으면 오류를 반환할 것입니다. 또한 post 변수들을 로컬 변수들로 전환하여 보겠습니다:

1
if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['email']) && !empty($_POST['email'])){
2
	$name = mysql_escape_string($_POST['name']); // Turn our post into a local variable

3
	$email = mysql_escape_string($_POST['email']); // Turn our post into a local variable

4
}

로컬 변수를 통해 데이터에 닿을 수 있습니다. 보다시피, MySQL 데이터베이스에 데이터를 삽입할 때 SQL 인젝션을 막기위해 쿼리 문자열 이스케이프를 추가했습니다.

"mysql_real_escape_string() 함수는 SQL문에서 사용하기 위해 문자열의 특수 문자를 이스케이프합니다."

정규 표현식

다음은 유효한 이메일 주소인지 확인 하는 작은 조각입니다.

1
	$name = mysql_escape_string($_POST['name']);
2
	$email = mysql_escape_string($_POST['email']);
3
	    		
4
	    		
5
	if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
6
		// Return Error - Invalid Email

7
	}else{
8
		// Return Success - Valid Email

9
	}

알아두어야할 점은 개인적으로 이 정규표현식을 쓰지 않았다는것입니다. 그것은 php.net 으로부터 얻은 작은 조각입니다.
기본적으로, 이메일이 다음과 같은 형식으로 쓰여졌는지 검사합니다:

1
	xxx@xxx.xxx

eregi 에서 이메일이 알파벳, 숫자들, 언더바, @, 마침표 문자들을 포함하는지 검사하는지 볼 수 있습니다. 그 문자들이 찾아지지 않으면 표현식은 "false"를 반환합니다. 기본적 오류 메세지들을 추가해 봅시다.

1
	if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
2
		// Return Error - Invalid Email

3
		$msg = 'The email you have entered is invalid, please try again.';
4
	}else{
5
		// Return Success - Valid Email

6
		$msg = 'Your account has been made, <br /> please verify it by clicking the activation link that has been send to your email.';
7
	}

보시다피 로컬 변수 "$msg"를 만들었는데 페이지 어디에서든 오류나 성공 메세지를 보는것을 가능하게 한다.
그리고 명령 텍스트와 폼 사이에 표시할 것이다.

1
	<!-- title and description -->	
2
	<h3>Signup Form</h3>
3
	<p>Please enter your name and email address to create your account</p>
4
		
5
	<?php 
6
		if(isset($msg)){  // Check if $msg is not empty

7
			echo '<div class="statusmsg">'.$msg.'</div>'; // Display our message and wrap it with a div with the class "statusmsg".

8
		} 
9
	?>
10
		
11
	<!-- start sign up form -->

우리의 상태 메시지에 약간 스타일 적용 위해 style.css에 추가.

1
#wrap .statusmsg{
2
	font-size: 12px; /* Set message font size  */
3
	padding: 3px; /* Some padding to make some more space for our text  */
4
	background: #EDEDED; /* Add a background color to our status message   */
5
	border: 1px solid #DFDFDF; /* Add a border arround our status message   */
6
}

단계 3 - 데이터베이스 생성과 연결 수립

데이터베이스 연결과 계정 데이터를 삽입할 테이블 생성이 필요합니다. 그래서 PHPMyAdmin에 가서 새 데이터베이스 registrations 를 생성하고 삽입하고 수정하기위해 데이터베이스에 접근권한을 가지는 사용자 계정을 생성합시다.

users 테이블을 5개 필드와 함께 생성:

필드들에 세부 사항들을 입력해야 합니다.

수동으로 데이터를 입력하기 원하지 않는 분들을 위해, 다음의 SQL 코드를 대신 실행 할 수 있습니다.

1
CREATE TABLE `users` (
2
`id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
3
`username` VARCHAR( 32 ) NOT NULL ,
4
`password` VARCHAR( 32 ) NOT NULL ,
5
`email` TEXT NOT NULL ,
6
`hash` VARCHAR( 32 ) NOT NULL ,
7
`active` INT( 1 ) NOT NULL DEFAULT '0'
8
) ENGINE = MYISAM ;

데이터베이스가 만들어졌습니다. PHP로 연결을 수립해야 합니다. 다음 줄 아래의 시작점에 코드를 쓸 것입니다.

1
<!-- start PHP code -->
2
<?php
3
// Establish database connection

데이터베이스 서버 연결에 다음 코드를 사용하고 registrations 데이터베이스를 선택할 것입니다. (기본 MySQL 연결)

1
mysql_connect("localhost", "username", "password") or die(mysql_error()); // Connect to database server(localhost) with username and password.

2
mysql_select_db("registrations") or die(mysql_error()); // Select registrations database.

데이터베이스에 연결을 수립했습니다. 다음단계로 가서 계정 세부를 삽입할 수 있게 되었습니다.


단계 4 - 계정 추가

전송된 계정 세부들을 데이터베이스에 활성 해시를 생성할 때가 되었습니다. 아래 코드를 쓰십시오:

1
// Return Success - Valid Email

2
$msg = 'Your account has been made, <br /> please verify it by clicking the activation link that has been send to your email.';

활성화 해시 (Activation Hash)

데이터베이스에 hash 라는 필드를 만들었습니다. 이 해시 크기는 32 문자입니다. 또한 이 코드를 사용자의 메일 주소로 보냅니다. 그 (해시를 포함하는)링크를 클릭하여 데이터베이스 내 하나와 맞춰봐서 검증할 수 있습니다. 로컬 변수 $hash 를 생성하고 임의의 md5 해시를 만듭시다.

1
$hash = md5( rand(0,1000) ); // Generate random 32 character hash and assign it to a local variable.

2
// Example output: f4552671f8909587cf485ea990207f3b

무엇을 했습니까? "rand"라는 PHP 함수를 사용하여 0에서 1000사이의 임의의 숫자를 생성했습니다. 다음엔 md5 함수가 이 숫자를 활성화 메일에 사용될 32자 문자열로 변환할 것입니다. md5 선택한것은 이 사례에서 깨는것이 불가능한 안전한 32 문자의 해시를 생성하기 때문입니다.

무작위 암호 생성

해야될 다음 일은 우리의 회원에게 무작위 암호를 생성하여 주는것 입니다.

1
$password = rand(1000,5000); // Generate random number between 1000 and 5000 and assign it to a local variable.

2
// Example output: 4568

다음 MySQL query를 사용하여 데이터베이스에 삽입합니다.

1
mysql_query("INSERT INTO users (username, password, email, hash) VALUES(

2
'". mysql_escape_string($name) ."', 

3
'". mysql_escape_string(md5($password)) ."', 

4
'". mysql_escape_string($email) ."', 

5
'". mysql_escape_string($hash) ."') ") or die(mysql_error());

MySQL 인젝션 방지를위해 모든 데이터에 mysql_escape_string 함수를 적용했습니다.
또한 보안을 위해 MD5 함수로 무작위 암호를 보안 해시로 변경했음을 알고 있어야 합니다. 예: 만약 "나쁜"사람이 데이터베이스 접근권한을 얻게되도 암호를 읽을 수 없습니다.

검사를 위해, 폼을 채우고 데이터베이스에 데이터가 삽입되는지 확인합니다.


단계 5 - 검증 메일 발송

후에 바로 데이터베이스에 정보를 삽입했습니다. 검증 링크와 함께 사용자에게 이메일을 보내야 합니다. PHP "mail" 함수로 그렇게 하도록 합시다.

1
$to      = $email; // Send email to our user

2
$subject = 'Signup | Verification'; // Give the email a subject 

3
$message = '

4


5
Thanks for signing up!

6
Your account has been created, you can login with the following credentials after you have activated your account by pressing the url below.

7


8
------------------------

9
Username: '.$name.'

10
Password: '.$password.'

11
------------------------

12


13
Please click this link to activate your account:

14
http://www.yourwebsite.com/verify.php?email='.$email.'&hash='.$hash.'

15


16
'; // Our message above including the link

17
					
18
$headers = 'From:noreply@yourwebsite.com' . "\r\n"; // Set from headers

19
mail($to, $subject, $message, $headers); // Send our email

메세지를 자세히 분석해봅시다:

1
Thanks for signing up!
2
Your account has been created, you can login with the following credentials after you have activated your account by pressing the url below.
3
4
------------------------
5
Username: '.$name.'
6
Password: '.$password.'
7
------------------------

위 코드에서 데이터가 포스팅되었을때 우리가 생성했던 로컬 변수를 사용해서 사용자에게 사용자명과 암호가 포함된 짧은 설명을 보냅니다.

1
Please click this link to activate your account:
2
http://www.yourwebsite.com/verify.php?email='.$email.'&hash='.$hash.'

이 코드 절에서 동적 링크를 생성했습니다. 그 결과는 다음과 같이 보여집니다: 

보다시피, 추측하기 힘든 견고한 url을 생성합니다. 이것은 사용자의 메일주소를 검증하는 매우 안전한 방법입니다.


단계 6 - 계정 활성

보다시피, url 은 verify.php 에 연결되니 만듭시다. index.php 사용했던 동일한 기본 템플릿을 사용합니다.
어쨌든, 템플릿에서 폼을 제거합니다.

1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2
3
<html xmlns="http://www.w3.org/1999/xhtml">
4
<head>
5
	<title>NETTUTS > Sign up</title>
6
	<link href="css/style.css" type="text/css" rel="stylesheet" />
7
</head>
8
<body>
9
	<!-- start header div -->	
10
	<div id="header">
11
		<h3>NETTUTS > Sign up</h3>
12
	</div>
13
	<!-- end header div -->	
14
	
15
	<!-- start wrap div -->	
16
	<div id="wrap">
17
	    <!-- start PHP code -->
18
	    <?php
19
	    
20
	    	mysql_connect("localhost", "tutorial", "password") or die(mysql_error()); // Connect to database server(localhost) with username and password.

21
			mysql_select_db("registrations") or die(mysql_error()); // Select registration database.

22
	    	
23
	    ?>
24
	    <!-- stop PHP Code -->
25
26
		
27
	</div>
28
	<!-- end wrap div -->	
29
</body>
30
</html>

처음 해야 될 일은 (이메일 & 해시) $_GET 변수들이 있는지 검사하는것 입니다.

1
if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !empty($_GET['hash'])){
2
	// Verify data

3
}else{
4
	// Invalid approach

5
}

지역 변수를 지정하고 MySQL 이스케이프 문자열을 사용하여 다시 한번 MySQL 주입 방지를 추가 합니다.

1
if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !empty($_GET['hash'])){
2
	// Verify data

3
	$email = mysql_escape_string($_GET['email']); // Set email variable

4
	$hash = mysql_escape_string($_GET['hash']); // Set hash variable

5
}

다음은 MySQL 쿼리로 데이터베이스의 데이터와 url 데이터를 비교 검사합니다.

1
$search = mysql_query("SELECT email, hash, active FROM users WHERE email='".$email."' AND hash='".$hash."' AND active='0'") or die(mysql_error()); 
2
$match  = mysql_num_rows($search);

위 코드에서 MySQL select 표현을 사용해서 이메일이 일치하는지 검사했습니다. 계정 상태의 "비활성" 여부도 동시에 확인 했습니다. 마지막으로 mysql_num_rows 사용하여 얼마나 많은 일치하는 레코드가 찾아지는지 측정했습니다. 해봅시다. 간단히 결과를 반환받아보기 위해 간단한 echo를 사용합니다.

1
$search = mysql_query("SELECT email, hash, active FROM users WHERE email='".$email."' AND hash='".$hash."' AND active='0'") or die(mysql_error()); 
2
$match  = mysql_num_rows($search);
3
4
echo $match; // Display how many matches have been found -> remove this when done with testing ;)

일치합니다! 결과를 바꾸기위해 메일을 변경하면 숫자 0 반환을 볼 수 있을것입니다.
$match 변수를 사용하여 계정을 활성하거나 일치하지 않을때 오류를 반환할 수 있습니다.

1
if($match > 0){
2
	// We have a match, activate the account

3
}else{
4
	// No match -> invalid url or account has already been activated.

5
}

계정을 활성하기 위해 MySQL 쿼리로 active 필드를 1로 변경해야 합니다.

1
// We have a match, activate the account

2
mysql_query("UPDATE users SET active='1' WHERE email='".$email."' AND hash='".$hash."' AND active='0'") or die(mysql_error());
3
echo '<div class="statusmsg">Your account has been activated, you can now login</div>';

업데이트를 위해 MySQL select 쿼리에서와 같은 조건을 사용했습니다. 메일, 해시 필드가 일치하고, 활성 필드가 0인 레코드의 활성을 1로 변경했습니다. 사용자에게 계정이 활성화되었음을 알리는 메세지를 돌려주겠습니다. "일치하는 데이터 없음" 부분에서 했던것과 같은 메세지를 추가 할 수 있습니다. 최종 코드는 다음 같습니다:

1
mysql_connect("localhost", "tutorial", "password") or die(mysql_error()); // Connect to database server(localhost) with username and password.

2
mysql_select_db("registrations") or die(mysql_error()); // Select registration database.

3
			
4
if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !empty($_GET['hash'])){
5
	// Verify data

6
	$email = mysql_escape_string($_GET['email']); // Set email variable

7
	$hash = mysql_escape_string($_GET['hash']); // Set hash variable

8
				
9
	$search = mysql_query("SELECT email, hash, active FROM users WHERE email='".$email."' AND hash='".$hash."' AND active='0'") or die(mysql_error()); 
10
	$match  = mysql_num_rows($search);
11
				
12
	if($match > 0){
13
		// We have a match, activate the account

14
		mysql_query("UPDATE users SET active='1' WHERE email='".$email."' AND hash='".$hash."' AND active='0'") or die(mysql_error());
15
		echo '<div class="statusmsg">Your account has been activated, you can now login</div>';
16
	}else{
17
		// No match -> invalid url or account has already been activated.

18
		echo '<div class="statusmsg">The url is either invalid or you already have activated your account.</div>';
19
	}
20
				
21
}else{
22
	// Invalid approach

23
	echo '<div class="statusmsg">Invalid approach, please use the link that has been send to your email.</div>';
24
}

아무런 문자열 없이 verify.php 를 방문하면 다음의 오류가 반겨줄 것입니다:


단계 7 - 로그인

마지막 단계에서, 기본 로그인 폼 생성법과 계정이 활성되었는지 검사하는법을 보여줄 것입니다. 먼저 login.php 파일을 전에 사용했던 기본 템플릿을 응용하여 생성하는데 이번엔 폼을 로그인폼으로 변경했습니다.

1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2
3
<html xmlns="http://www.w3.org/1999/xhtml">
4
<head>
5
	<title>NETTUTS > Sign up</title>
6
	<link href="css/style.css" type="text/css" rel="stylesheet" />
7
</head>
8
<body>
9
	<!-- start header div -->	
10
	<div id="header">
11
		<h3>NETTUTS > Sign up</h3>
12
	</div>
13
	<!-- end header div -->	
14
	
15
	<!-- start wrap div -->	
16
	<div id="wrap">
17
	    <!-- start PHP code -->
18
	    <?php
19
	    
20
	    	mysql_connect("localhost", "tutorial", "password") or die(mysql_error()); // Connect to database server(localhost) with username and password.

21
			mysql_select_db("registrations") or die(mysql_error()); // Select registration database.

22
				
23
	    	
24
	    ?>
25
	    <!-- stop PHP Code -->
26
	
27
		<!-- title and description -->	
28
		<h3>Login Form</h3>
29
		<p>Please enter your name and password to login</p>
30
		
31
		<?php 
32
			if(isset($msg)){ // Check if $msg is not empty

33
				echo '<div class="statusmsg">'.$msg.'</div>'; // Display our message and add a div around it with the class statusmsg

34
			} ?>
35
		
36
		<!-- start sign up form -->	
37
		<form action="" method="post">
38
			<label for="name">Name:</label>
39
			<input type="text" name="name" value="" />
40
			<label for="password">Password:</label>
41
			<input type="password" name="password" value="" />
42
			
43
			<input type="submit" class="submit_button" value="Sign up" />
44
		</form>
45
		<!-- end sign up form -->	
46
		
47
	</div>
48
	<!-- end wrap div -->	
49
</body>
50
</html>

폼은 기본적 html 이고 대개의 가입폼과 같으니 부연설명이 불필요합니다. 로그인 스크립트 코드를 작성할 때입니다. MySQL 연결 코드 아래에 작성할 것입니다. 가입 폼에서 했던것과 같이 시작해봅시다.

1
if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['password']) && !empty($_POST['password'])){
2
	// Both fields are being posted and there not empty

3
}

전송된 데이터를 검사하여 비어있지 않도록 했습니다.
post 데이터를 위한 로컬 변수들을 생성합시다:

1
if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['password']) && !empty($_POST['password'])){
2
	$username = mysql_escape_string($_POST['name']); // Set variable for the username

3
	$password = mysql_escape_string(md5($_POST['password'])); // Set variable for the password and convert it to an MD5 hash.

4
}

로컬 변수들을 생성하였고 암호를 데이터베이스에 저장했던 암호 해시와 비교하기 위해 md5 해시로 변경하였습니다.
이제, "users" 테이블에 연결하여 입력한 데이터가 올바른지 검증합시다.

1
if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['password']) && !empty($_POST['password'])){
2
	$username = mysql_escape_string($_POST['name']);
3
	$password = mysql_escape_string(md5($_POST['password']));
4
				
5
	$search = mysql_query("SELECT username, password, active FROM users WHERE username='".$username."' AND password='".$password."' AND active='1'") or die(mysql_error()); 
6
	$match  = mysql_num_rows($search);
7
			}

username, password 에 맞는 활성정보를 데이터베이스에서 select 할 MySQL 쿼리를 작성했습니다.
AND active='1' 는 중요합니다! 계정이 활성화되었을때만 로그인할 수 있도록 확실히 해줍니다. 얼마나 많이 검색되는지 MySQL num rows 를 사용합니다.

1
if($match > 0){
2
	$msg = 'Login Complete! Thanks';
3
	// Set cookie / Start Session / Start Download etc...

4
}else{
5
	$msg = 'Login Failed! Please make sure that you enter the correct details and that you have activated your account.';
6
}

위 코드에서 로그인이 성공했는지 아닌지 검사했습니다.


마침

이 학습의 끝입니다! 즐기셨기를 바라며 그랬다면 아래에 의견을 남겨주세요!

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.