jason-gao/http

🌐 Nette Http:HTTP 请求、响应和会话的抽象。提供数据清理和URL、cookie操作的实用工具。

v3.0.0-alpha1 2017-02-02 00:52 UTC

README

Downloads this Month Build Status Build Status Windows Coverage Status Latest Stable Version License

介绍

HTTP 请求和响应封装在 Nette\Http\RequestNette\Http\Response 对象中,它们提供舒适的API,同时充当清理过滤器。

文档可以在 网站 上找到。

安装

推荐的安装方式是通过Composer

composer require nette/http

它需要PHP版本5.6,并支持PHP 7.2。dev-master版本需要PHP 7.1。

HTTP 请求

Nette 清理用户从控制台发送的数据以及无效字符。

请求的URL作为 [api: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 |urls] 对象返回。

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)

上传的文件封装成 [api: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 = array('hu', 'pl', 'en'); // languages supported in application

echo $httpRequest->detectLanguage($langs); // en

RequestFactory 和 URL 过滤

当前HTTP请求的对象由 [api:Nette\Http\RequestFactory] 创建。其行为可以被修改。可以使用过滤器清理掉由于各种网站实现不完善评论系统而可能进入URL的字符。

$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);

然后我们让工厂生成一个新的 httpRequest,并将其存储在系统容器中

// $container is a system container
$container->addService('httpRequest', $requestFactory->createHttpRequest());

HTTP 响应

是否还可以发送头部或更改状态代码由 isSent() 方法决定。如果它返回true,则无法发送另一个头部或更改状态代码。

在这种情况下,任何尝试发送头部或更改代码都将引发 Nette\InvalidStateException。[警告]

可以通过这种方式发送和检索 [Response status code | http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10]

$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) 更改 Content-Type 响应头部

$httpResponse->setContentType('text/plain', 'UTF-8');

通过 redirect($url, $code=302) 方法重定向到另一个URL。不要忘记在之后终止脚本!

$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。它们的详细描述可以在PHP手册的[php:setcookie]函数中找到。