企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 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手册中找到。