PHP 8.4.2 Released!

来自 PHP 之外的变量

HTML 表单(GET 和 POST)

当一个表单提交给 PHP 脚本时,表单中的信息会自动在脚本中可用。有几个方法访问此信息,例如:

示例 #1 一个简单的 HTML 表单

<form action="foo.php" method="POST">
    Name:  <input type="text" name="username"><br />
    Email: <input type="text" name="email"><br />
    <input type="submit" name="submit" value="Submit me!" />
</form>

只有两种方法可以访问 HTML 表单中的数据。以下列出了当前有效的方法:

示例 #2 从简单的 POST HTML 表单访问数据

<?php
echo $_POST['username'];
echo
$_REQUEST['username'];
?>

使用 GET 表单也类似,只不过要用适当的 GET 预定义变量。GET 也适用于 QUERY_STRING(URL 中在“?”之后的信息)。因此,举例说,http://www.example.com/test.php?id=3 包含有可用 $_GET['id'] 来访问的 GET 数据。参见 $_REQUEST

注意:

变量名中的点和空格被转换成下划线。例如 <input name="a.b" /> 变成了 $_REQUEST["a_b"]

PHP 也理解表单变量上下文中的数组(参见相关常见问题)。例如可以将相关的变量编成组,或者用此功能从多选输入框中取得值。例如,将表单 POST 给自己并在提交时显示数据:

示例 #3 更复杂的表单变量

<?php
if ($_POST) {
echo
'<pre>';
echo
htmlspecialchars(print_r($_POST, true));
echo
'</pre>';
}
?>
<form action="" method="post">
Name: <input type="text" name="personal[name]" /><br />
Email: <input type="text" name="personal[email]" /><br />
Beer: <br />
<select multiple name="beer[]">
<option value="warthog">Warthog</option>
<option value="guinness">Guinness</option>
<option value="stuttgarter">Stuttgarter Schwabenbräu</option>
</select><br />
<input type="submit" value="submit me!" />
</form>

注意: 如果外部变量名以有效的数组语法开头,则将会忽略尾随字符。例如,<input name="foo[bar]baz"> 变为 $_REQUEST['foo']['bar']

IMAGE SUBMIT 变量名

当提交表单时,可以用一幅图像代替标准的提交按钮,用类似这样的标记:

<input type="image" src="image.gif" name="sub" />

当用户点击到图像中的某处时,相应的表单会被传送到服务器,并加上两个变量 sub_xsub_y。它们包含了用户点击图像的坐标。有经验的用户可能会注意到被浏览器发送的实际变量名包含的是一个点而不是下划线(即 sub.x 和 sub.y),但 PHP 自动将点转换成了下划线。

HTTP Cookie

PHP 透明地支持 » RFC 6265定义中的 HTTP cookies。Cookies 是一种在远端浏览器端存储数据并能追踪或识别再次访问的用户的机制。可以用 setcookie() 函数设定 cookies。Cookies 是 HTTP 信息头中的一部分,因此 SetCookie 函数必须在向浏览器发送任何输出之前调用。对于 header() 函数也有同样的限制。Cookie 数据会在相应的 cookie 数据数组中可用,例如 $_COOKIE$_REQUEST。更多细节和例子见 setcookie() 手册页面。

注意: 自 PHP 7.2.34、7.3.23 和 7.4.11 起,出于安全原因,传入 cookie 的 name 不再进行 url 解码。

如果要将多个值赋给单个 cookie 变量,可以将其赋成数组。例如:

<?php
setcookie
("MyCookie[foo]", 'Testing 1', time()+3600);
setcookie("MyCookie[bar]", 'Testing 2', time()+3600);
?>

尽管 MyCookie 在脚本中是单个数组,这将会建立两个单独的 cookie。如果只需为一个 cookie 设定多个值,考虑先在值上使用 serialize()explode()

注意,除非路径或者域不同,cookie 将替换浏览器中先前的同名 cookie。因此对于购物车程序,可以保留一个计数器并一起传递,即

示例 #4 一个 setcookie() 的示例

<?php
if (isset($_COOKIE['count'])) {
$count = $_COOKIE['count'] + 1;
} else {
$count = 1;
}
setcookie('count', $count, time()+3600);
setcookie("Cart[$count]", $item, time()+3600);
?>

变量名中的点

通常,PHP 不会改变传递给脚本中的变量名。然而应该注意到点(句号)不是 PHP 变量名中的合法字符。至于原因,看看:

<?php
$varname
.ext; /* 非法变量名 */
?>
这时,解析器看到是一个名为 $varname 的变量,后面跟着一个字符串连接运算符,后面跟着一个裸字符串(即没有加引号的字符串,且不匹配任何已知的健名或保留字)'ext'。很明显这不是想要的结果。

出于此原因,要注意 PHP 将会自动将变量名中的点替换成下划线。

确定变量类型

因为 PHP 会判断变量类型并在需要时进行转换(通常情况下),因此在某一时刻给定的变量是何种类型并不明显。PHP 包括几个函数可以判断变量的类型,例如:gettype()is_array()is_float()is_int()is_object()is_string()。参见类型一章。

HTTP 是一种文本协议,大多数(可能不是全部)超全局数组中的内容(如 $_POST$_GET)将保留为字符串。PHP 不会尝试将值转换为特定类型。在下面的示例中,$_GET["var1"] 将包含字符串“null”,而 $_GET["var2"] 将包含字符串“123”。

/index.php?var1=null&var2=123

更新日志

版本 说明
7.2.34, 7.3.23, 7.4.11 出于安全原因,传入 cookie 的 name 不再进行 URL 解码。

添加备注

用户贡献的备注 2 notes

up
19
Anonymous
16 years ago
The full list of field-name characters that PHP converts to _ (underscore) is the following (not just dot):
chr(32) ( ) (space)
chr(46) (.) (dot)
chr(91) ([) (open square bracket)
chr(128) - chr(159) (various)

PHP irreversibly modifies field names containing these characters in an attempt to maintain compatibility with the deprecated register_globals feature.
up
6
krydprz at iit dot edu
19 years ago
This post is with regards to handling forms that have more than one submit button.

Suppose we have an HTML form with a submit button specified like this:

<input type="submit" value="Delete" name="action_button">

Normally the 'value' attribute of the HTML 'input' tag (in this case "Delete") that creates the submit button can be accessed in PHP after post like this:

<?php
$_POST
['action_button'];
?>

We of course use the 'name' of the button as an index into the $_POST array.

This works fine, except when we want to pass more information with the click of this particular button.

Imagine a scenario where you're dealing with user management in some administrative interface. You are presented with a list of user names queried from a database and wish to add a "Delete" and "Modify" button next to each of the names in the list. Naturally the 'value' of our buttons in the HTML form that we want to display will be "Delete" and "Modify" since that's what we want to appear on the buttons' faceplates.

Both buttons (Modify and Delete) will be named "action_button" since that's what we want to index the $_POST array with. In other words, the 'name' of the buttons along cannot carry any uniquely identifying information if we want to process them systematically after submit. Since these buttons will exist for every user in the list, we need some further way to distinguish them, so that we know for which user one of the buttons has been pressed.

Using arrays is the way to go. Assuming that we know the unique numerical identifier of each user, such as their primary key from the database, and we DON'T wish to protect that number from the public, we can make the 'action_button' into an array and use the user's unique numerical identifier as a key in this array.

Our HTML code to display the buttons will become:

<input type="submit" value="Delete" name="action_button[0000000002]">
<input type="submit" value="Modify" name="action_button[0000000002]">

The 0000000002 is of course the unique numerical identifier for this particular user.

Then when we handle this form in PHP we need to do the following to extract both the 'value' of the button ("Delete" or "Modify") and the unique numerical identifier of the user we wish to affect (0000000002 in this case). The following will print either "Modify" or "Delete", as well as the unique number of the user:

<?php
$submitted_array
= array_keys($_POST['action_button']);
echo (
$_POST['action_button'][$submitted_array[0]] . " " . $submitted_array[0]);
?>

$submitted_array[0] carries the 0000000002.
When we index that into the $_POST['action_button'], like we did above, we will extract the string that was used as 'value' in the HTML code 'input' tag that created this button.

If we wish to protect the unique numerical identifier, we must use some other uniquely identifying attribute of each user. Possibly that attribute should be encrypted when output into the form for greater security.

Enjoy!
To Top