19e3b6cda2d739943b905fe953c1dffc6402088a
[mdref/mdref-http] / http / Message / Body / addForm.md
1 # http\Message\Body http\Message\Body::addForm([array $fields = NULL[, array $files = NULL]])
2
3 Add form fields and files to the message body.
4
5 > **Note:** Currently, http\Message\Body::addForm() creates "multipart/form-data" bodies.
6
7 ## Params:
8
9 * array $fields = NULL
10 List of form fields to add.
11
12 * array $files = NULL
13 List of form files to add.
14
15 $fields must look like:
16
17 [
18 "field_name" => "value",
19 "multi_field" => [
20 "value1",
21 "value2"
22 ]
23 ]
24
25 $files must look like:
26
27 [
28 [
29 "name" => "field_name",
30 "type" => "content/type",
31 "file" => "/path/to/file.ext"
32 ], [
33 "name" => "field_name2",
34 "type" => "text/plain",
35 "file" => "file.ext",
36 "data" => "string"
37 ], [
38 "name" => "field_name3",
39 "type" => "image/jpeg",
40 "file" => "file.ext",
41 "data" => fopen("/home/mike/Pictures/mike.jpg","r")
42 ]
43
44 As you can see, a file structure must contain a "file" entry, which holds a file path, and an optional "data" entry, which may either contain a resource to read from or the actual data as string.
45
46 ## Returns:
47
48 * http\Message\Body, self.
49
50 ## Throws:
51
52 * http\Exception\InvalidArgumentException
53 * http\Exception\RuntimeException
54
55 ## Example:
56
57 <?php
58 $body = new http\Message\Body;
59 $body->addForm([
60 "field_name" => "value",
61 "multi_field" => [
62 "value1",
63 "value2"
64 ]
65 ], [
66 [
67 "name" => "field_name",
68 "type" => "application/octet-stream",
69 "file" => "/run/gpm.pid"
70 ], [
71 "name" => "field_name2",
72 "type" => "text/plain",
73 "file" => "signature.txt",
74 "data" => "-- \nMike\n"
75 ], [
76 "name" => "field_name3",
77 "type" => "image/jpeg",
78 "file" => "picture.jpg",
79 "data" => fopen("/home/mike/Pictures/mike.jpg","r")
80 ]
81 ]);
82
83 echo $body;
84 ?>
85
86 Yields:
87
88 --32260b4b.3fea9114
89 Content-Disposition: form-data; name="field_name"
90
91 value
92 --32260b4b.3fea9114
93 Content-Disposition: form-data; name="multi_field[0]"
94
95 value1
96 --32260b4b.3fea9114
97 Content-Disposition: form-data; name="multi_field[1]"
98
99 value2
100 --32260b4b.3fea9114
101 Content-Disposition: form-data; name="field_name"; filename="gpm.pid"
102 Content-Transfer-Encoding: binary
103 Content-Type: application/octet-stream
104
105 316
106
107 --32260b4b.3fea9114
108 Content-Disposition: form-data; name="field_name2"; filename="signature.txt"
109 Content-Transfer-Encoding: binary
110 Content-Type: text/plain
111
112 --
113 Mike
114
115 --32260b4b.3fea9114
116 Content-Disposition: form-data; name="field_name3"; filename="picture.jpg"
117 Content-Transfer-Encoding: binary
118 Content-Type: image/jpeg
119
120 ...JPEG...
121 --32260b4b.3fea9114--