Php 简明教程

PHP - $_POST

$_POST 是 PHP 中的一个预定义的超全局变量。它是由 HTTP POST 方法(在请求中使用 URLEncoded 或 multipart/form-data 内容类型)传递给 URL 的键值对关联数组。

$_POST is one of the predefined or superglobal variables in PHP. It is an associative array of key-value pairs passed to a URL by the HTTP POST method that uses URLEncoded or multipart/form-data content-type in the request.

  1. $HTTP_POST_VARS also contains the same information as $_POST, but is not a superglobal, and now been deprecated.

  2. The easiest way to send data to a server with POST request is specifying the method attribute of HTML form as POST.

假设浏览器中的 URL 为“http://localhost/hello.php”,method=POST 在 HTML 表单“hello.html”中设置如下 −

Assuming that the URL in the browser is "http://localhost/hello.php", method=POST is set in a HTML form "hello.html" as below −

<html>
<body>
   <form action="hello.php" method="post">
      <p>First Name: <input type="text" name="first_name"/> </p>
      <p>Last Name: <input type="text" name="last_name" /> </p>
      <input type="submit" value="Submit" />
   </form>
</body>
</html>

此练习的“hello.php”脚本(位于文档根目录文件夹中)如下:

The "hello.php" script (in the document root folder) for this exercise is as follows:

<?php
   echo "<h3>First name: " . $_POST['first_name'] . "<br /> " .
   "Last Name: " . $_POST['last_name'] . "</h3>";
?>

现在,在你的浏览器中打开 http://localhost/hello.html 。你应该在屏幕上获得以下输出 −

Now, open http://localhost/hello.html in your browser. You should get the following output on the screen −

php $ post 1

当您按下 Submit 按钮时,数据将使用 POST 方法提交至“hello.php”。

As you press the Submit button, the data will be submitted to "hello.php" with the POST method.

php $ post 2

您还可以将 HTML 表单与 hello.php 中的 PHP 代码混合使用,并使用“PHP_SELF”变量将其表单数据发布给自己 -

You can also mix the HTML form with PHP code in hello.php, and post the form data to itself using the "PHP_SELF" variable −

<html>
<body>
   <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
      <p>First Name: <input type="text" name="first_name"/> </p> <br />
      <p>Last Name: <input type="text" name="last_name" /></p>
      <input type="submit" value="Submit" />
   </form>
   <?php
      echo "<h3>First Name: " . $_POST['first_name'] . "<br /> " .
      "Last Name: " . $_POST['last_name'] . "</h3>";
   ?>
</body>
</html>

它将生成以下 output

It will produce the following output

php $ post 3