This repository has been archived by the owner on Nov 16, 2022. It is now read-only.
forked from nette/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http-request-response.texy
232 lines (160 loc) · 6.83 KB
/
http-request-response.texy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
HTTP Request & Response
***********************
.[perex]
HTTP request and response are encapsulated in [api:Nette\Http\Request] and [Response|api:Nette\Http\Response] objects which offer comfortable API and also act as
sanitization filter.
HTTP Request
==============
Nette Framework cleans out data sent by user from control and invalid characters. It also removes any //magic_quotes//.
HTTP request which is an object of class [Nette\Http\Request |api:] we don't create directly, but we receive it as a service from a [DI container |di-usage].
/--php
$httpRequest = $container->getByType('Nette\Http\Request');
\--
The URL of the request is available as [api:Nette\Http\UrlScript] instance:
/--php
$url = $httpRequest->getUrl();
echo $url; // e.g. http://nette.org/en/documentation?action=edit
echo $url->host; // nette.org
\--
Determine current HTTP method:
/--php
echo $httpRequest->getMethod(); // GET, POST, HEAD, PUT
if ($httpRequest->isMethod('GET')) ...
\--
Is the connection encrypted (HTTPS)?
/--php
echo $httpRequest->isSecured() ? 'yes' : 'no';
\--
Is this an AJAX request?
/--php
echo $httpRequest->isAjax() ? 'yes' : 'no';
\--
What is the user's IP address?
/--php
echo $httpRequest->getRemoteAddress(); // user's IP address
echo $httpRequest->getRemoteHost(); // and its DNS translation
\--
What URL the user came from? Returned as [Nette\Http\Url |urls] object.
/--php
echo $httpRequest->getReferer()->host;
\--
Request parameters:
/--php
$get = $httpRequest->getQuery(); // array of all URL parameters
$id = $httpRequest->getQuery('id'); // returns GET parameter 'id' (or NULL)
$post = $httpRequest->getPost(); // array of all POST parameters
$id = $httpRequest->getPost('id'); // returns POST parameter 'id' (or NULL)
$cookies = $httpRequest->getCookies(); // array of all cookies
$sessId = $httpRequest->getCookie('sess_id'); // returns the cookie (or NULL)
\--
Uploaded files are encapsulated into [api:Nette\Http\FileUpload] objects:
/--php
$files = $httpRequest->getFiles(); // array of all uploaded files
$file = $httpRequest->getFile('avatar'); // returns one file
echo $file->getName(); // name of the file sent by user
echo $file->getSanitizedName(); // the name without dangerous characters
\--
HTTP headers are also accessible:
/--php
// returns associative array of HTTP headers
$headers = $httpRequest->getHeaders();
// returns concrete header (case-insensitive)
$userAgent = $httpRequest->getHeader('User-Agent');
\--
A useful method is `detectLanguage()`. You can pass it an array with languages supported by application and it returns the one preferred by browser.
It is not magic, the method just uses the `Accept-Language` header.
/--php
// Header sent by browser: Accept-Language: cs,en-us;q=0.8,en;q=0.5,sl;q=0.3
$langs = array('hu', 'pl', 'en'); // languages supported in application
echo $httpRequest->detectLanguage($langs); // en
\--
RequestFactory and URL filtering
------------------
Object holding current HTTP request is created by [api:Nette\Http\RequstFactory]. Its behavior can be modified.
It's possible to clean up URLs from characters that can get into them because of poorly implemented comment systems on various other websites by using filters:
/--php
$requestFactory = new Nette\Http\RequestFactory;
// remove spaces from path
$requestFactory->addUrlFilter('%20', '', PHP_URL_PATH);
// remove dot, comma or right parenthesis form the end of the URL
$requestFactory->addUrlFilter('[.,)]$');
// clean the path from duplicated slashes (default filter)
$requestFactory->addUrlFilter('/{2,}', '/', PHP_URL_PATH);
\--
And then we let the factory generate a new `httpRequest` and we store it in a system container:
/--php
// $container is a system container
$container->addService('httpRequest', $requestFactory->createHttpRequest());
\--
HTTP response
============
HTTP response which is an object of class [Nette\Http\Response |api:] we don't create directly, but we receive it as a service from a [DI container |di-usage].
/--php
$httpResponse = $container->getByType('Nette\Http\Response');
\--
Whether it is still possible to send headers or change the status code tells the `isSent()` method. If it returns TRUE,
it won't be possible to send another header or change the status code.
In that case, any attempt to send header or change code invokes `Nette\InvalidStateException`. .[caution]
[Response status code | http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10] can be sent and retrieved this way:
/--php
$httpResponse->setCode(Nette\Http\Response::S404_NOT_FOUND);
echo $httpResponse->getCode(); // 404
\--
For better source code readability it is recommended to use predefined constants instead of actual numbers:
/--
Http\IResponse::S200_OK
Http\IResponse::S204_NO_CONTENT
Http\IResponse::S300_MULTIPLE_CHOICES
Http\IResponse::S301_MOVED_PERMANENTLY
Http\IResponse::S302_FOUND
Http\IResponse::S303_SEE_OTHER
Http\IResponse::S303_POST_GET
Http\IResponse::S304_NOT_MODIFIED
Http\IResponse::S307_TEMPORARY_REDIRECT
Http\IResponse::S400_BAD_REQUEST
Http\IResponse::S401_UNAUTHORIZED
Http\IResponse::S403_FORBIDDEN
Http\IResponse::S404_NOT_FOUND
Http\IResponse::S410_GONE
Http\IResponse::S500_INTERNAL_SERVER_ERROR
Http\IResponse::S501_NOT_IMPLEMENTED
Http\IResponse::S503_SERVICE_UNAVAILABLE
\--
Method `setContentType($type, $charset=NULL)` changes `Content-Type` response header:
/--php
$httpResponse->setContentType('text/plain', 'UTF-8');
\---
Redirection to another URL is done by `redirect($url, $code=302)` method. Do not forget to terminate the script afterwards!
/--php
$httpResponse->redirect('http://example.com');
exit;
\---
To set the document expiration date, we can use `setExpiration()` method. The parameter is either text data, number of seconds or a timestamp:
/--php
// browser cache expires in one hour
$httpResponse->setExpiration('+ 1 hours');
\---
Now we send the HTTP response header:
/--php
$httpResponse->setHeader('Pragma', 'no-cache');
// or if we want to send the same header more times with different values
$httpResponse->addHeader('Pragma', 'no-cache');
\---
Sent headers are also available:
/--php
// returns associative array of headers
$headers = $httpResponse->getHeaders();
// returns concrete header (case-insensitive)
$pragma = $httpResponse->getHeader('Pragma');
\--
There are two methods for cookie manipulation: `setCookie()` and `deleteCookie()`.
/--php
// setCookie($name, $value, $time, [$path, [$domain, [$secure, [$httpOnly]]]])
$httpResponse->setCookie('lang', 'en', '100 days'); // send cookie
// deleteCookie($name, [$path, [$domain, [$secure]]])
$httpResponse->deleteCookie('lang'); // delete cookie
\---
These two methods can take more parameters: `$path` (subdirectory where the cookie will be available),
`$domain` and `$secure`. Their detailed description can be found in PHP manual for [php:setcookie] function.
{{themeicon: icon-communication.png}}
{{composer: nette/http}}