PHP 안전한 이메일
이전 장의 PHP 이메일 스크립트에는 취약점이 있습니다.
PHP 이메일 주입
먼저, 이전 장의 PHP 코드를 보세요:
<html> <body> <?php if (isset($_REQUEST['email'])) //이메일이 입력되었을 경우 이메일을 보냅니다 { //이메일을 보냅니다 $email = $_REQUEST['email'] ; $subject = $_REQUEST['subject'] ; $message = $_REQUEST['message'] ; mail("someone@example.com", "Subject: $subject", $message, "From: $email" ); echo "Thank you for using our mail form"; } else //이메일이 입력되지 않았을 경우 양식을 표시합니다 { echo "<form method='post' action='mailform.php'> 이메일: <input name='email' type='text' /><br /> 제목: <input name='subject' type='text' /><br /> 메시지:<br /> <textarea name='message' rows='15' cols='40'> </textarea><br /> <input type='submit' /> </form>"; } ?> </body> </html>
이 코드가 문제는, 권한이 없는 사용자가 양식을 통해 이메일 헤더에 데이터를 삽입할 수 있다는 점입니다.
사용자가 양식의 입력 필드에 이러한 텍스트를 추가하면 어떤 일이 일어날까요?
someone@example.com%0ACc:person2@example.com %0ABcc:person3@example.com,person3@example.com, anotherperson4@example.com,person5@example.com %0ABTo:person6@example.com
mail() 함수는 이제 이메일 헤더에 추가된 Cc:, Bcc: 및 To: 필드에 위의 텍스트를 포함합니다. 사용자가 제출 버튼을 클릭하면 이 이메일이 모든 주소로 전송됩니다!
PHP 이메일 주입 방지
이메일 주입을 방지하는 가장 좋은 방법은 입력을 검증하는 것입니다.
아래의 코드는 이전 장과 유사하지만, 입력된 form의 email 필드의 입력��증 프로그램을 추가했습니다:
<html> <body> <?php function spamcheck($field) { //filter_var()은 이메일을 정리 $field=filter_var($field, FILTER_SANITIZE_EMAIL); //filter_var()은 이메일을 확인 if(filter_var($field, FILTER_VALIDATE_EMAIL)) { return TRUE; } else { return FALSE; } } if (isset($_REQUEST['email'])) //"email"이 입력되었을 경우 진행 //이메일 주소가 무효인지 확인 $mailcheck = spamcheck($_REQUEST['email']); if ($mailcheck==FALSE) { echo "Invalid input"; } else //이메일 보내기 $email = $_REQUEST['email'] ; $subject = $_REQUEST['subject'] ; $message = $_REQUEST['message'] ; mail("someone@example.com", "Subject: $subject", $message, "From: $email" ); echo "Thank you for using our mail form"; } } else //if "email" is not filled out, display the form echo "<form method='post' action='mailform.php'> 이메일: <input name='email' type='text' /><br /> 제목: <input name='subject' type='text' /><br /> 메시지:<br /> <textarea name='message' rows='15' cols='40'> </textarea><br /> <input type='submit' /> </form>"; } ?> </body> </html>
위의 코드에서는 PHP 필터를 사용하여 입력을 검증했습니다:
- FILTER_SANITIZE_EMAIL 문자열에서 이메일의 불법 문자를 제거
- FILTER_VALIDATE_EMAIL 이메일 주소를 검증
우리의 PHP 필터이 장에서 필터에 대한 더 많은 내용을 읽을 수 있습니다.