28. PHP Form 검증
Form 검증(validation)
HTML form 요소는 텍스트 입력, 체크박스, 라디오 버튼 등 다양한 input 요소를 포함할 수 있다.
input 요소별로 사용자가 입력한 데이터가 적합한 데이터인지를 검사하는 검증 규칙을 설정할 수 있다.
회원가입 예제
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>이름 : <input type="text" name="name"></p>
<p>성별 :
<input type="radio" name="gender" value="female">여자
<input type="radio" name="gender" value="male">남자
</p>
<p>이메일 : <input type="text" name="email"></p>
<p>홈페이지 : <input type="text" name="website"></p>
<p>관심 있는 분야 :
<input type="checkbox" name="favtopic[]" value="movie"> 영화
<input type="checkbox" name="favtopic[]" value="music"> 음악
<input type="checkbox" name="favtopic[]" value="game"> 게임
<input type="checkbox" name="favtopic[]" value="coding"> 코딩
</p>
<p>기타 : <textarea name="comment"></textarea></p>
<p><input type="submit" value="전송"></p>
</form>
|
cs |
위에 예제에서 method의 속성 값으로 "post"를 사용하고 있다.
1
|
<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
|
cs |
$_SERVER["PHP_SELF"]는 PHP에서 제공하는 슈퍼 글로벌 변수로 PHP_SELF를 사용하면 현재 실행 중인 PHP 스크립트 파일 이름을 반환한다.
htmlspecialchars() 함수는 인수로 전달받은 문자열에 포함된 특수 문자들을 HTML 엔티티로 변환해 준다.
www.php.net/manual/ja/function.htmlspecialchars.php
PHP: htmlspecialchars - Manual
if your goal is just to protect your page from Cross Site Scripting (XSS) attack, or just to show HTML tags on a web page (showing on the page, for example), then using htmlspecialchars() is good enough and better than using htmlentities(). A minor point
www.php.net
htmlspecialchars를 사용함으로써 입력 문자열에 사용자가 나쁜 의도로 HTML 코드를 삽입하는 것을 막을 수 있다.
form 통해 전송된 데이터를 PHP로 처리하는 코드
1
2
3
4
5
6
7
8
9
10
|
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$gender = $_POST["gender"];
$email = $_POST["email"];
$website = $_POST["website"];
$favtopic = $_POST["favtopic"];
$comment = $_POST["comment"];
}
?>
|
cs |
처리한 데이터를 화면에 출력하는 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<?php
echo "<h2>입력된 회원 정보</h2>";
echo "이름 : ".$name."<br>";
echo "성별 : ".$gender."<br>";
echo "이메일 : ".$email."<br>";
echo "홈페이지 : ".$website."<br>";
echo "관심 있는 분야 : ";
if (!empty($favtopic)) {
foreach ($favtopic as $value) {
echo $value." ";
}
}
echo "<br>기타 : ".$comment;
?>
|
cs |
관심 있는 분야는 체크박스로 통해 여러 개를 입력받을 수 있으므로 배열을 통해서 처리해 주었다.
하지만 체크 박스가 하나도 선택되지 않은 상태로 전송하게 되면 오류를 발생할 것이다.
그래서 empty나 isset을 통해 변수에 값이 들어있는지 체크해주는 습관을 길러야 한다.