当前位置: 首页>>代码示例>>PHP>>正文


PHP Response::getHeaders方法代码示例

本文整理汇总了PHP中Zend\Http\Response::getHeaders方法的典型用法代码示例。如果您正苦于以下问题:PHP Response::getHeaders方法的具体用法?PHP Response::getHeaders怎么用?PHP Response::getHeaders使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Zend\Http\Response的用法示例。


在下文中一共展示了Response::getHeaders方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: onRoute

 public function onRoute(MvcEvent $e)
 {
     $request = $e->getRequest();
     if (!$request instanceof HttpRequest) {
         return;
     }
     $application = $e->getApplication();
     $serviceLocator = $application->getServiceManager();
     // Load the configuration for maintenance mode
     if ($serviceLocator->has('MaintenanceConfig')) {
         $config = $serviceLocator->get('MaintenanceConfig');
     } else {
         $config = new Config();
     }
     if (!$config->isEnabled()) {
         // Maintenance mode is disabled.
         return;
     }
     // Check the white list
     if ($request instanceof PhpRequest) {
         $address = $request->getServer('REMOTE_ADDR', null);
     } else {
         $address = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
     }
     if (!empty($address)) {
         if (in_array($address, $config->getWhitelist())) {
             return;
         }
     }
     // Render the maintenance layout
     $renderer = new PhpRenderer();
     if ($serviceLocator->has('ViewHelperManager')) {
         $renderer->setHelperPluginManager($serviceLocator->get('ViewHelperManager'));
     }
     $resolver = new TemplateMapResolver();
     $resolver->add('maintenance', $config->getTemplate());
     $renderer->setResolver($resolver);
     $content = $renderer->render('maintenance');
     // Set the response
     $response = $e->getResponse();
     if (!$response instanceof HttpResponse) {
         $response = new HttpResponse();
     }
     $statusCode = $config->getStatusCode();
     $response->setStatusCode($statusCode);
     if ($statusCode === 503 && !$response->getHeaders()->has('Retry-After')) {
         $retryDate = $config->getRetryAfter();
         if ($retryDate instanceof DateTime) {
             $retryAfter = new RetryAfter();
             $retryAfter->setDate($retryDate);
             $response->getHeaders()->addHeader($retryAfter);
         }
     }
     $response->setContent($content);
     $e->setResponse($response);
     // Return the response
     return $response;
 }
开发者ID:zend-modules,项目名称:maintenance,代码行数:58,代码来源:MaintenanceListener.php

示例2: vCardAction

 public function vCardAction()
 {
     $contact = $this->contactService->find($this->params('id'));
     if (!$contact) {
         return $this->notFoundAction();
     }
     $builder = new VCardBuilder();
     switch (true) {
         case $contact instanceof Company:
             $vcard = $builder->buildCompany($contact);
             break;
         case $contact instanceof Person:
             $vcard = $builder->buildPerson($contact);
             break;
         default:
             throw new RuntimeException('Invalid type provided.');
     }
     $data = $vcard->serialize();
     $response = new Response();
     $response->setStatusCode(Response::STATUS_CODE_200);
     $response->setContent($data);
     $headers = $response->getHeaders();
     $headers->addHeaderLine('Content-Disposition', 'attachment; filename="' . $contact->getDisplayName() . '.vcf"');
     $headers->addHeaderLine('Content-Length', strlen($data));
     $headers->addHeaderLine('Content-Type', 'text/plain');
     return $response;
 }
开发者ID:zource,项目名称:zource,代码行数:27,代码来源:VCard.php

示例3: plugin_preview_action

function plugin_preview_action()
{
    global $vars;
    $page = isset($vars['page']) ? $vars['page'] : '';
    $modified = 0;
    $response = new Response();
    if (!empty($page)) {
        $wiki = Factory::Wiki($page);
        if ($wiki->isReadable()) {
            $source = $wiki->get();
            array_splice($source, 10);
            $response->setStatusCode(Response::STATUS_CODE_200);
            $response->setContent('<' . '?xml version="1.0" encoding="UTF-8"?' . ">\n" . RendererFactory::factory($source));
            $headers = Header::getHeaders('text/xml', $wiki->time());
        } else {
            $response->setStatusCode(Response::STATUS_CODE_404);
            $headers = Header::getHeaders('text/xml');
        }
    } else {
        $response->setStatusCode(Response::STATUS_CODE_404);
        $headers = Header::getHeaders('text/xml');
    }
    $response->getHeaders()->addHeaders($headers);
    header($response->renderStatusLine());
    foreach ($response->getHeaders() as $_header) {
        header($_header->toString());
    }
    echo $response->getBody();
    exit;
}
开发者ID:logue,项目名称:pukiwiki_adv,代码行数:30,代码来源:preview.inc.php

示例4: assertResponseNotInjected

 protected function assertResponseNotInjected()
 {
     $content = $this->response->getContent();
     $headers = $this->response->getHeaders();
     $this->assertEmpty($content);
     $this->assertFalse($headers->has('content-type'));
 }
开发者ID:wizzvet,项目名称:ZffHtml2pdf,代码行数:7,代码来源:Html2PdfStrategyTest.php

示例5: __invoke

 /**
  * Encode data as JSON and set response header
  *
  * @param  mixed $data
  * @param  array $jsonOptions Options to pass to JsonFormatter::encode()
  * @return string|void
  */
 public function __invoke($data, array $jsonOptions = array())
 {
     $data = JsonFormatter::encode($data, null, $jsonOptions);
     if ($this->response instanceof Response) {
         $headers = $this->response->getHeaders();
         $headers->addHeaderLine('Content-Type', 'application/json');
     }
     return $data;
 }
开发者ID:shabbirvividads,项目名称:magento2,代码行数:16,代码来源:Json.php

示例6: testSave

 public function testSave()
 {
     $expectedDate = new \DateTime('2015-01-01');
     $request = new Request('GET', 'http://example.com');
     $response = new Response();
     $listener = new TimetableCookieListener($request, $response);
     $event = new TimetableManagerEvent();
     $event->setPointInTime($expectedDate);
     $listener->storeTime($event);
     $this->assertTrue($response->getHeaders()->has('Set-Cookie'));
     $cookie = current($response->getHeaders()->get('Set-Cookie'));
     $this->assertEquals($expectedDate, new \DateTime($cookie->getValue()));
 }
开发者ID:nathansalter,项目名称:verona,代码行数:13,代码来源:TimetableCookieListenerTest.php

示例7: handleResponse

 /**
  * Parses the HTTP response from a userinfo request.
  * 
  * @param Http\Response $httpResponse
  * @throws HttpAuthenticateException
  * @throws HttpErrorStatusException
  * @throws InvalidResponseFormatException
  * @throws Exception\InvalidResponseException
  */
 public function handleResponse(Http\Response $httpResponse)
 {
     if (!$httpResponse->isSuccess()) {
         $statusCode = $httpResponse->getStatusCode();
         if (401 === $statusCode && ($authenticateHeader = $httpResponse->getHeaders()->get($this->wwwAuthenticateHeaderName)->current())) {
             $params = $this->parseAuthenticateHeaderValue($authenticateHeader->getFieldValue());
             if (isset($params['error'])) {
                 $this->setError($this->getErrorFactory()->createErrorFromArray($params));
                 return;
             }
             throw new HttpAuthenticateException(sprintf("Missing error information in WWW-Authenticate header: %s", $authenticateHeader->getFieldValue()));
         }
         throw new HttpErrorStatusException(sprintf("Error status response from server: %s", $statusCode));
     }
     try {
         $responseData = $this->getJsonCoder()->decode($httpResponse->getBody());
     } catch (\Exception $e) {
         throw new InvalidResponseFormatException('The HTTP response does not contain valid JSON', null, $e);
     }
     try {
         $this->response = $this->getResponseFactory()->createResponse($responseData);
     } catch (\Exception $e) {
         throw new Exception\InvalidResponseException(sprintf("Invalid response: [%s] %s", get_class($e), $e->getMessage()), null, $e);
     }
 }
开发者ID:publicitas-deployment,项目名称:php-openid-connect-client,代码行数:34,代码来源:ResponseHandler.php

示例8: testSendHeadersTwoTimesSendsOnlyOnce

 /**
  * @runInSeparateProcess
  */
 public function testSendHeadersTwoTimesSendsOnlyOnce()
 {
     if (!function_exists('xdebug_get_headers')) {
         $this->markTestSkipped('Xdebug extension needed, skipped test');
     }
     $headers = array('Content-Length: 2000', 'Transfer-Encoding: chunked');
     $response = new Response();
     $response->getHeaders()->addHeaders($headers);
     $mockSendResponseEvent = $this->getMock('Zend\\Mvc\\ResponseSender\\SendResponseEvent', array('getResponse'));
     $mockSendResponseEvent->expects($this->any())->method('getResponse')->will($this->returnValue($response));
     $responseSender = $this->getMockForAbstractClass('Zend\\Mvc\\ResponseSender\\AbstractResponseSender');
     $responseSender->sendHeaders($mockSendResponseEvent);
     $sentHeaders = xdebug_get_headers();
     $diff = array_diff($sentHeaders, $headers);
     if (count($diff)) {
         $header = array_shift($diff);
         $this->assertContains('XDEBUG_SESSION', $header);
         $this->assertEquals(0, count($diff));
     }
     $expected = array();
     if (version_compare(phpversion('xdebug'), '2.2.0', '>=')) {
         $expected = xdebug_get_headers();
     }
     $responseSender->sendHeaders($mockSendResponseEvent);
     $this->assertEquals($expected, xdebug_get_headers());
 }
开发者ID:pnaq57,项目名称:zf2demo,代码行数:29,代码来源:AbstractResponseSenderTest.php

示例9: testInvokeForDigestAuthAddsAuthorizationHeader

    public function testInvokeForDigestAuthAddsAuthorizationHeader()
    {
        $httpAuth = new HttpAuth(array(
            'accept_schemes' => 'digest',
            'realm' => 'User Area',
            'digest_domains' => '/',
            'nonce_timeout' => 3600,
        ));
        $httpAuth->setDigestResolver(new HttpAuth\FileResolver(__DIR__ . '/../TestAsset/htdigest'));
        $this->listener->setHttpAdapter($httpAuth);

        $this->listener->__invoke($this->mvcAuthEvent);

        $authHeaders = $this->response->getHeaders()->get('WWW-Authenticate');
        $authHeader = $authHeaders[0];
        $this->assertInstanceOf('Zend\Http\Header\HeaderInterface', $authHeader);
        $this->assertRegexp(
            '#^Digest realm="User Area", domain="/", '
            . 'nonce="[a-f0-9]{32}", '
            . 'opaque="e66aa41ca5bf6992a5479102cc787bc9", '
            . 'algorithm="MD5", '
            . 'qop="auth"$#',
            $authHeader->getFieldValue()
        );
    }
开发者ID:jbarentsen,项目名称:drb,代码行数:25,代码来源:DefaultAuthenticationListenerTest.php

示例10: createResponse

 /**
  * Creates the response to be returned for a QR Code
  * @param $content
  * @param $contentType
  * @return HttpResponse
  */
 protected function createResponse($content, $contentType)
 {
     $resp = new HttpResponse();
     $resp->setStatusCode(200)->setContent($content);
     $resp->getHeaders()->addHeaders(array('Content-Length' => strlen($content), 'Content-Type' => $contentType));
     return $resp;
 }
开发者ID:acelaya,项目名称:zf2-acqrcode,代码行数:13,代码来源:QrCodeController.php

示例11: sendHeaders

 /**
  * Immediately send headers from a Zend\Http\Response
  * 
  * @param ZendResponse $zresponse Zend\Http\Response
  * 
  * @return void
  */
 public static function sendHeaders(ZendResponse $zresponse)
 {
     $headers = $zresponse->getHeaders()->toArray();
     foreach ($headers as $key => $value) {
         header(sprintf('%s: %s', $key, $value));
     }
 }
开发者ID:fwk,项目名称:security,代码行数:14,代码来源:RequestBridge.php

示例12: onRoute

 public function onRoute(MvcEvent $e)
 {
     $serviceManager = $e->getApplication()->getServiceManager();
     $routeMatchName = $e->getRouteMatch()->getMatchedRouteName();
     if (strpos($routeMatchName, '.rest.') !== false || strpos($routeMatchName, '.rpc.') !== false) {
         return;
     }
     $config = $serviceManager->get('Config');
     $identityGuards = $config['zource_guard']['identity'];
     $needsIdentity = null;
     foreach ($identityGuards as $guard => $needed) {
         if (fnmatch($guard, $routeMatchName)) {
             $needsIdentity = $needed;
             break;
         }
     }
     if ($needsIdentity === null) {
         throw new RuntimeException(sprintf('The identity guard "%s" has not been configured.', $routeMatchName));
     }
     if (!$needsIdentity) {
         return;
     }
     $authenticationService = $serviceManager->get('Zend\\Authentication\\AuthenticationService');
     if ($authenticationService->hasIdentity()) {
         return;
     }
     $returnUrl = $e->getRouter()->assemble([], ['name' => $routeMatchName, 'force_canonical' => true, 'query' => $e->getRequest()->getUri()->getQuery()]);
     $url = $e->getRouter()->assemble([], ['name' => 'login', 'query' => ['redir' => $returnUrl]]);
     $response = new Response();
     $response->setStatusCode(Response::STATUS_CODE_302);
     $response->getHeaders()->addHeaderLine('Location: ' . $url);
     return $response;
 }
开发者ID:zource,项目名称:zource,代码行数:33,代码来源:IdentityGuard.php

示例13: decode

 /**
  * {@inheritdoc}
  */
 public function decode(Response $response)
 {
     $headers = $response->getHeaders();
     if (!$headers->has('Content-Type')) {
         $exception = new Exception\InvalidResponseException('Content-Type missing');
         $exception->setResponse($response);
         throw $exception;
     }
     /* @var $contentType \Zend\Http\Header\ContentType */
     $contentType = $headers->get('Content-Type');
     switch (true) {
         case $contentType->match('*/json'):
             $payload = Json::decode($response->getBody(), Json::TYPE_ARRAY);
             break;
             //TODO: xml
             //             case $contentType->match('*/xml'):
             //                 $xml = Security::scan($response->getBody());
             //                 $payload = Json::decode(Json::encode((array) $xml), Json::TYPE_ARRAY);
             //                 break;
         //TODO: xml
         //             case $contentType->match('*/xml'):
         //                 $xml = Security::scan($response->getBody());
         //                 $payload = Json::decode(Json::encode((array) $xml), Json::TYPE_ARRAY);
         //                 break;
         default:
             throw new Exception\InvalidFormatException(sprintf('The "%s" media type is invalid or not supported', $contentType->getMediaType()));
             break;
     }
     $this->lastPayload = $payload;
     if ($contentType->match('*/hal+*')) {
         return $this->extractResourceFromHal($payload, $this->getPromoteTopCollection());
     }
     //else
     return (array) $payload;
 }
开发者ID:matryoshka-model,项目名称:service-api,代码行数:38,代码来源:Hal.php

示例14: onDispatchError

 /**
  * Get the exception and optionally set status code, reason message and additional errors
  *
  * @internal
  * @param  MvcEvent $event
  * @return void
  */
 public function onDispatchError(MvcEvent $event)
 {
     $exception = $event->getParam('exception');
     if (isset($this->exceptionMap[get_class($exception)])) {
         $exception = $this->createHttpException($exception);
     }
     // We just deal with our Http error codes here !
     if (!$exception instanceof HttpExceptionInterface || $event->getResult() instanceof HttpResponse) {
         return;
     }
     // We clear the response for security purpose
     $response = new HttpResponse();
     $response->getHeaders()->addHeaderLine('Content-Type', 'application/json');
     $exception->prepareResponse($response);
     // NOTE: I'd like to return a JsonModel instead, and let ZF handle the request, but I couldn't make
     // it work because for unknown reasons, the Response get replaced "somewhere" in the MVC workflow,
     // so the simplest is simply to do that
     $content = ['status_code' => $response->getStatusCode(), 'message' => $response->getReasonPhrase()];
     if ($errors = $exception->getErrors()) {
         $content['errors'] = $errors;
     }
     $response->setContent(json_encode($content));
     $event->setResponse($response);
     $event->setResult($response);
     $event->stopPropagation(true);
 }
开发者ID:omusico,项目名称:zfr-rest,代码行数:33,代码来源:HttpExceptionListener.php

示例15: _challengeClient

    /**
     * Challenge Client
     *
     * Sets a 401 or 407 Unauthorized response code, and creates the
     * appropriate Authenticate header(s) to prompt for credentials.
     *
     * @return Authentication\Result Always returns a non-identity Auth result
     */
    protected function _challengeClient()
    {
        if ($this->imaProxy) {
            $statusCode = 407;
            $headerName = 'Proxy-Authenticate';
        } else {
            $statusCode = 401;
            $headerName = 'WWW-Authenticate';
        }

        $this->response->setStatusCode($statusCode);

        // Send a challenge in each acceptable authentication scheme
        $headers = $this->response->getHeaders();
        if (in_array('basic', $this->acceptSchemes)) {
            $headers->addHeaderLine($headerName, $this->_basicHeader());
        }
        if (in_array('digest', $this->acceptSchemes)) {
            $headers->addHeaderLine($headerName, $this->_digestHeader());
        }
        return new Authentication\Result(
            Authentication\Result::FAILURE_CREDENTIAL_INVALID,
            array(),
            array('Invalid or absent credentials; challenging client')
        );
    }
开发者ID:Robert-Xie,项目名称:php-framework-benchmark,代码行数:34,代码来源:Http.php


注:本文中的Zend\Http\Response::getHeaders方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。