PHP表单总结

一、表单基础:

htmlspecialchars(变量) 函数把特殊字符转换为 HTML 实体。这意味着 < 和 > 之类的 HTML 字符会被替换为 < 和 > 。这样可防止攻击者通过在表单中注入 HTML 或 JavaScript 代码(跨站点脚本攻击)对代码进行利用。

$_SERVER[“PHP_SELF”] 是一种超全局变量,它返回当前执行脚本的文件名

empty(变量) 判断是否为空

preg_match(“表达式”,变量) 判断匹配字符,表达式类似于正则表达式

isset(变量) 函数作用 isset函数是检测变量是否设置,例如单选按钮


二、应用实例:



// 定义变量并设置为空值
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
$value=0;
$value=$_POST["value"];
if($value!=0){
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
  }

  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
  }

  if (empty($_POST["website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["website"]);
  }

  if (empty($_POST["comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["comment"]);
  }

  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
  }
}
    }

?>



<form method="post" action="PHP_SELF"]);?>">
<input type="hidden" name="value" value="1" />
Name: <input type="text" name="name">
<span class="error" style="color:red;">*  echo $nameErr;?>span>
<br><br>
E-mail:
<input type="text" name="email">
<span class="error" style="color:red;">*  echo $emailErr;?>span>
<br><br>
Website:
<input type="text" name="website">
<span class="error"> echo $websiteErr;?>span>
<br><br>
<label>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
<span class="error" style="color:red;">*  echo $genderErr;?>span>
<br><br>
<input type="submit" name="submit" value="Submit"> 

form>

这基本是w3cschool的源代码,只加了一个标量。因为这两段代码位于同一文件下,避免在未提交的情况下执行php代码。

你可能感兴趣的:(PHP)