实际上,您想要做的正是多部分消息相对于$_POST 数组的工作方式。
考虑以下 HTML 表单:
<form action="/somefile.php" method="post" enctype="multipart/form-data">
<input name="text1" type="text" />
<input name="text2" type="text" />
<input name="text3" type="text" />
<input name="file" type="file" />
<input type="submit" />
</form>
现在假设我们用value1、value2 和value3 填充三个文本输入,我们选择一个名为file.txt 的文件,然后按提交。这将导致一个看起来像这样的请求:
POST /somefile.php HTTP/1.1
Host: somehost.com
Accept: */*
User-Agent: MyBrowser/1.0
Content-Type: multipart/form-data; boundary="this-is-a-boundary-string"
--this-is-a-boundary-string
Content-Dispostion: form-data; name="text1"
value1
--this-is-a-boundary-string
Content-Dispostion: form-data; name="text2"
value2
--this-is-a-boundary-string
Content-Dispostion: form-data; name="text3"
value3
--this-is-a-boundary-string
Content-Dispostion: form-data; name="file"; filename="file.txt"
Content-Type: text/plain
This is the contents of file.txt
--this-is-a-boundary-string--
当我们在 PHP 中查看它时,如果我们 print_r($_POST); 我们应该得到这样的结果:
Array
(
[text1] => value1
[text2] => value2
[text3] => value3
)
...如果我们print_r($_FILES);:
Array
(
[file] => Array
(
[name] => file.txt
[type] => text/plain
[size] => 32
[tmp_name] => /tmp/dskhfwe43232.tmp
[error] => 0
)
)
...所以你可以看到,消息中Content-Disposition: header 不包含filename="" 元素的部分被添加到$_POST 数组中,而那些带有一个的部分被视为文件上传并添加到$_FILES。
在构建multipart/form-data 消息以发送到服务器时,我发现构建您正在模仿请求的 HTML 表单并根据该 HTML 表单的行为方式构建您的 HTTP 消息是最容易的。