# HTTP請求和響應
HTTP請求和響應封裝在Nette \ Http \ Request和Response對象中,這些對象提供了舒適的API,并且還充當了殺毒過濾器。
## HTTP Request
Nette框架清除用戶從控制和無效字符發送的數據。 它也刪除任何magic_quotes。
HTTP請求,它是類Nette \ Http \ Request的對象,我們不直接創建,但是我們從DI容器接收它作為服務。
~~~
$httpRequest = $container->getByType('Nette\Http\Request');
~~~
請求的URL可用為Nette \ Http \ UrlScript實例:
~~~
$url = $httpRequest->getUrl();
echo $url; // e.g. https://nette.org/en/documentation?action=edit
echo $url->host; // nette.org
~~~
確定當前的HTTP方法:
~~~
echo $httpRequest->getMethod(); // GET, POST, HEAD, PUT
if ($httpRequest->isMethod('GET')) ...
~~~
連接是否已加密(HTTPS)?
~~~
echo $httpRequest->isSecured() ? 'yes' : 'no';
~~~
這是一個AJAX請求嗎?
~~~
echo $httpRequest->isAjax() ? 'yes' : 'no';
~~~
用戶的IP地址是什么?
~~~
echo $httpRequest->getRemoteAddress(); // user's IP address
echo $httpRequest->getRemoteHost(); // and its DNS translation
~~~
用戶來自哪個URL? 作為Nette \ Http \ Url對象返回。
~~~
echo $httpRequest->getReferer()->host;
~~~
請求參數:
~~~
$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)
~~~
上傳的文件封裝到Nette \ Http \ FileUpload對象中:
~~~
$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標頭:
~~~
// returns associative array of HTTP headers
$headers = $httpRequest->getHeaders();
// returns concrete header (case-insensitive)
$userAgent = $httpRequest->getHeader('User-Agent');
~~~
一個有用的方法是detectLanguage()。 你可以傳遞一個數組的應用程序支持的語言,它返回瀏覽器首選的一個。 這不是魔術,方法只是使用Accept-Language頭。
~~~
// Header sent by browser: Accept-Language: cs,en-us;q=0.8,en;q=0.5,sl;q=0.3
$langs = ['hu', 'pl', 'en']; // languages supported in application
echo $httpRequest->detectLanguage($langs); // en
~~~
### RequestFactory和URL過濾
對象保持當前HTTP請求由Nette \ Http \ RequstFactory創建。 其行為可以修改。 可以通過使用過濾器來清除可能進入其中的字符的URL,因為在其他網站上執行的評論系統效果不佳:
~~~
$requestFactory = new Nette\Http\RequestFactory;
// remove spaces from path
$requestFactory->urlFilters['path']['%20'] = '';
// remove dot, comma or right parenthesis form the end of the URL
$requestFactory->urlFilters['url']['[.,)]$'] = '';
// clean the path from duplicated slashes (default filter)
$requestFactory->urlFilters['path']['/{2,}'] = '/';
~~~
然后我們讓工廠生成一個新的http請求,并將它存儲在系統容器中:
~~~
// $container is a system container
$container->addService('httpRequest', $requestFactory->createHttpRequest());
~~~
### HTTP響應
HTTP響應,它是一個類Nette \ Http \ Response的對象,我們不直接創建,但是我們從DI容器接收它作為服務。
~~~
$httpResponse = $container->getByType('Nette\Http\Response');
~~~
是否仍然可能發送頭或更改狀態代碼告訴isSent()方法。 如果它返回TRUE,將不可能發送另一個頭或更改狀態代碼。
響應狀態代碼可以這樣發送和檢索:
~~~
$httpResponse->setCode(Nette\Http\Response::S404_NOT_FOUND);
echo $httpResponse->getCode(); // 404
~~~
為了更好的源代碼可讀性,建議使用預定義常量而不是實際數字:
~~~
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
~~~
方法setContentType($ type,$ charset = NULL)changes Content-Type響應頭:
~~~
$httpResponse->setContentType('text/plain', 'UTF-8');
~~~
重定向到另一個URL是通過redirect($ url,$ code = 302)方法。 不要忘了終止腳本!
~~~
$httpResponse->redirect('http://example.com');
exit;
~~~
要設置文檔到期日期,我們可以使用setExpiration()方法。 參數是文本數據,秒數或時間戳:
~~~
// browser cache expires in one hour
$httpResponse->setExpiration('+ 1 hours');
~~~
現在我們發送HTTP響應頭:
~~~
$httpResponse->setHeader('Pragma', 'no-cache');
// or if we want to send the same header more times with different values
$httpResponse->addHeader('Pragma', 'no-cache');
~~~
發送標頭也可用:
~~~
// returns associative array of headers
$headers = $httpResponse->getHeaders();
// returns concrete header (case-insensitive)
$pragma = $httpResponse->getHeader('Pragma');
~~~
有兩種cookie操作方法:setCookie()和deleteCookie()。
~~~
// 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
~~~
這兩個方法可以使用更多的參數:$ path(cookie將可用的子目錄),$ domain和$ secure。 他們的詳細描述可以在setcookie函數的PHP手冊中找到。
- Nette簡介
- 快速開始
- 入門
- 主頁
- 顯示文章詳細頁
- 文章評論
- 創建和編輯帖子
- 權限驗證
- 程序員指南
- MVC應用程序和控制器
- URL路由
- Tracy - PHP調試器
- 調試器擴展
- 增強PHP語言
- HTTP請求和響應
- 數據庫
- 數據庫:ActiveRow
- 數據庫和表
- Sessions
- 用戶授權和權限
- 配置
- 依賴注入
- 獲取依賴關系
- DI容器擴展
- 組件
- 字符串處理
- 數組處理
- HTML元素
- 使用URL
- 表單
- 驗證器
- 模板
- AJAX & Snippets
- 發送電子郵件
- 圖像操作
- 緩存
- 本土化
- Nette Tester - 單元測試
- 與Travis CI的持續集成
- 分頁
- 自動加載
- 文件搜索:Finder
- 原子操作