Home > Backend Development > PHP Tutorial > 使用 PHP 验证表单数据

使用 PHP 验证表单数据

WBOY
Release: 2016-06-23 13:27:33
Original
1054 people have browsed it

当用户提交表单时,做到以下两件事是非常有必要:

使用 PHP trim() 函数去除用户输入数据中不必要的字符 (如:空格,tab,换行)。

使用PHP stripslashes()函数去除用户输入数据中的反斜杠 (\)


<!DOCTYPE HTML> <html><head></head><body> <?php// define variables and set to empty values$name = $email = $gender = $comment = $website = "";if ($_SERVER["REQUEST_METHOD"] == "POST"){   $name = test_input($_POST["name"]);   $email = test_input($_POST["email"]);   $website = test_input($_POST["website"]);   $comment = test_input($_POST["comment"]);   $gender = test_input($_POST["gender"]);}function test_input($data){   $data = trim($data);   $data = stripslashes($data);   $data = htmlspecialchars($data);   return $data;}?><h2>PHP Form Validation Example</h2><form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">    Name: <input type="text" name="name">   <br><br>   E-mail: <input type="text" name="email">   <br><br>   Website: <input type="text" name="website">   <br><br>   Comment: <textarea name="comment" rows="5" cols="40"></textarea>   <br><br>   Gender:   <input type="radio" name="gender" value="female">Female   <input type="radio" name="gender" value="male">Male   <br><br>   <input type="submit" name="submit" value="Submit"> </form><?phpecho "<h2>Your Input:</h2>";echo $name;echo "<br>";echo $email;echo "<br>";echo $website;echo "<br>";echo $comment;echo "<br>";echo $gender;?></body></html>
Copy after login



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template