HTTP Server Request (PSR-7)


PSR-7 HTTP Server Request - 图1

Overview

Phalcon\Http\Message\ServerRequest is an implementation of the PSR-7 HTTP messaging interface as defined by PHP-FIG.

PSR-7 HTTP Server Request - 图2

These interface implementations have been created to establish a standard between middleware implementations. Applications often need to receive data from external sources such as the users using the application. The Phalcon\Http\Message\ServerRequest represents an incoming, server-side HTTP request. Per the HTTP specification, this interface includes properties for each of the following:

  • Headers
  • HTTP method
  • Message body
  • Protocol version
  • URIAdditionally, it encapsulates all data as it has arrived at the application from the CGI and/or PHP environment, including:

  • The values represented in $_SERVER.

  • Any cookies provided (generally via $_COOKIE)
  • Query string arguments (generally via $_GET, or as parsed via parse_str())
  • Upload files, if any (as represented by $_FILES)
  • Deserialized body parameters (generally from $_POST)$_SERVER values are treated as immutable, as they represent application state at the time of request; as such, no methods are provided to allow modification of those values. The other values provide such methods, as they can be restored from $_SERVER or the request body, and may need treatment during the application (e.g., body parameters may be deserialized based on content type).

Additionally, this interface recognizes the utility of introspecting a request to derive and match additional parameters (e.g., via URI path matching, decrypting cookie values, deserializing non-form-encoded body content, matching authorization headers to users, etc). These parameters are stored in an “attributes” property.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. use Phalcon\Http\Message\Uri;
  4. $request = new Request();
  5. $uri = new Uri('https://api.phalcon.io/companies/1');
  6. $request = new ServerRequest();
  7. $request = $request
  8. ->withHeader('Content-Type', ['application/json'])
  9. ->withMethod('GET')
  10. ->withProtocolVersion('1.1')
  11. ->withUploadedFiles($_FILES)
  12. ->withUri($uri)
  13. ;

We are creating a new Phalcon\Http\Message\ServerRequest object and a new Phalcon\Http\Message\Uri object with the target URL. Following that we define the method (GET), a protocol version, uploaded files and additional headers.

The above example can be implemented by only using the constructor parameters:

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest(
  4. 'GET',
  5. 'https://api.phalcon.io/companies/1',
  6. $_SERVER,
  7. 'php://input',
  8. [
  9. 'Content-Type' => 'application/json',
  10. ],
  11. $_COOKIE,
  12. $_GET,
  13. $_FILES,
  14. 'some body',
  15. '1.2'
  16. );

The ServerRequest object created is immutable, meaning it will never change. Any call to methods prefixed with with* will return a clone of the object to maintain immutability, as per the standard.

Constructor

  1. public function __construct(
  2. [string $method = "GET"
  3. [, mixed $uri = null
  4. [, array serverParams = [],
  5. [, mixed body = "php://input",
  6. [, mixed headers = [],
  7. [, array cookies = [],
  8. [, array queryParams = [],
  9. [, array uploadFiles = [],
  10. [, mixed parsedBody = null,
  11. [, string protocol = "1.1"]]]]]]]]]]
  12. )

The constructor accepts parameters allowing you to create the object with certain properties populated. You can define the target HTTP method, the URL, the body as well as the headers. All parameters are optional.

  • method - defaults to GET. The supported methods are: GET, CONNECT, DELETE, HEAD, OPTIONS, PATCH, POST, PUT, TRACE
  • uri - An instance of Phalcon\Http\Message\Uri or a URL.
  • serverParams - A key value array, with key as the server variable name and value as the server value
  • body - It defaults to php://input. The method accepts either an object that implements the StreamInterface interface or a string such as the name of the stream. The default mode for the stream is w+b. If a non valid stream is passed, an InvalidArgumentException is thrown
  • headers - A key value array, with key as the header name and value as the header value.
  • cookies - A key value array, with key as the cookie name and value as the cookie value.
  • queryParams - A key value array, with key as the query parameter name and value as the query parameter value.
  • uploadFiles - An array of uploaded files ($_FILES)
  • parsedBody - The parsed body of the server request
  • protocol - A string representing the protocol (1.0, 1.1)
  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest(
  4. 'GET',
  5. 'https://api.phalcon.io/companies/1',
  6. $_SERVER,
  7. 'php://input',
  8. [
  9. 'Content-Type' => 'application/json',
  10. ],
  11. $_COOKIE,
  12. $_GET,
  13. $_FILES,
  14. 'some body',
  15. '1.2'
  16. );

Getters

getAttribute()

Returns a single derived request attribute. The method gets a single attribute as produced by getAttributes(). The first parameter defines the name of the attribute that we need to retrieve. You can also supply a second variable which will be used as a default, in case the requested attribute name does not exist.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest();
  4. $request = $request
  5. ->withAttribute('one', 'two')
  6. ;
  7. echo $request->getAttribute('one'); // 'twu'
  8. echo $request->getAttribute('three', 'four'); // 'four'

getAttributes()

Returns an array with all the attributes derived from the request. These request “attributes” may be used to allow injection of any parameters derived from the request: e.g., the results of path match operations; the results of decrypting cookies; the results of deserializing non-form-encoded message bodies; etc. Attributes will be application and request specific, and can be mutable.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest();
  4. $request = $request
  5. ->withAttribute('one', 'two')
  6. ;
  7. var_dump(
  8. $request->getAttributes()
  9. );
  10. // [
  11. // 'one' => 'two',
  12. // ]

getBody()

Returns the body as a StreamInterface object

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. use Phalcon\Http\Message\Stream;
  4. $jwtToken = 'abc.def.ghi';
  5. $fileName = dataFolder('/assets/stream/mit.txt');
  6. $stream = new Stream($fileName, 'rb');
  7. $request = new ServerRequest('GET', null, [], $stream);
  8. echo $request->getBody(); // '/assets/stream/mit.txt'

getCookieParams()

Returns the cookies of the server request. The returned array is compatible with the structure of the $_COOKIE superglobal.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest(
  4. 'GET',
  5. 'https://api.phalcon.io/companies/1',
  6. [],
  7. 'php://input',
  8. [],
  9. [
  10. 'cookie-one' => 'cookie-value-one',
  11. ]
  12. );
  13. var_dump(
  14. $request->getCookieParams()
  15. );
  16. // [
  17. // 'cookie-one' => 'cookie-value-one',
  18. // ]

getHeader()

Returns an array of all the header values of the passed case insensitive header name. If the string parameter representing the header name requested is not present, an empty array is returned.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest(
  4. 'POST',
  5. 'https://api.phalcon.io/companies/1',
  6. [],
  7. 'php://memory',
  8. [
  9. 'Content-Type' => 'application/json',
  10. ]
  11. );
  12. echo $request->getHeader('content-Type'); // ['application/json']
  13. echo $request->getHeader('unknown'); // []

getHeaderLine()

Returns all of the header values of the given case-insensitive header name as a string concatenated together using a comma. If the string parameter representing the header name requested, an empty string is returned.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest(
  4. 'POST',
  5. 'https://api.phalcon.io/companies/1',
  6. [],
  7. 'php://memory',
  8. [
  9. 'Content-Type' => [
  10. 'application/json',
  11. 'application/html',
  12. ],
  13. ]
  14. );
  15. echo $request->getHeaderLine('content-Type'); // 'application/json,application/html'

getHeaders()

Returns an array with all the message header values. The keys represent the header name as it will be sent over the wire, and each value is an array of strings associated with the header. While header names are not case-sensitive, this method preserves the exact case in which headers were originally specified.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest(
  4. 'POST',
  5. 'https://api.phalcon.io/companies/1',
  6. [],
  7. 'php://memory',
  8. [
  9. 'Content-Type' => [
  10. 'application/json',
  11. 'application/html',
  12. ],
  13. ]
  14. );
  15. var_dump(
  16. $request->getHeaders()
  17. );
  18. // [
  19. // 'Content-Type' => [
  20. // 'application/json',
  21. // 'application/html',
  22. // ],
  23. // ]

getMethod()

Returns the method as a string

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest('POST');
  4. echo $request->getMethod(); // POST

getParsedBody()

Returns any parameters provided in the request body. If the request Content-Type is either application/x-www-form-urlencoded or multipart/form-data, and the request method is POST, this method will return the contents of $_POST. Otherwise, this method may return any results of deserializing the request body content; as parsing returns structured content, the potential types will be arrays or objects only. If there is no body content, null will be returned.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest(
  4. 'POST',
  5. 'https://api.phalcon.io/companies/1',
  6. $_SERVER,
  7. 'php://input',
  8. [
  9. 'Content-Type' => 'application/x-www-form-urlencoded',
  10. ],
  11. $_COOKIE,
  12. $_GET,
  13. $_FILES,
  14. $_POST,
  15. '1.2'
  16. );
  17. var_dump(
  18. $this->getParsedBody()
  19. );
  20. // $_POST

getProtocolVersion()

Returns the protocol version as as string (default 1.1)

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest();
  4. echo $request->getProtocolVersion(); // '1.1'

getQueryParams()

Returns an array with the deserialized query string arguments, if any. Note that the query params might not be in sync with the URI or server parameters. If you need to ensure you are only getting the original values, you may need to parse the query string from getUri()->getQuery() or from the QUERY_STRING server parameter.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest();
  4. $request = $request->withQueryParams(
  5. [
  6. 'param' => 'value',
  7. ]
  8. );
  9. var_dump(
  10. $request->getQueryParams()
  11. );
  12. // [
  13. // 'param' => 'value',
  14. // ]

getRequestTarget()

Returns a string representing the message’s request-target either as it will appear (for clients), as it appeared at request (for servers), or as it was specified for the instance (see withRequestTarget()). In most cases, this will be the origin-form of the composed URI, unless a value was provided to the concrete implementation (see withRequestTarget()).

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest();
  4. $request = $request->withRequestTarget('/test');
  5. echo $request->getRequestTarget(); // '/test'

getServerParams()

Returns an array of data related to the incoming request environment, typically derived from PHP’s $_SERVER superglobal. This data however is not required to originate from the $_SERVER superglobal.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest(
  4. 'POST',
  5. 'https://api.phalcon.io/companies/1',
  6. $_SERVER
  7. );
  8. var_dump(
  9. $this->getServerParams()
  10. );
  11. // $_POST
  12. $request = new ServerRequest(
  13. 'POST',
  14. 'https://api.phalcon.io/companies/1',
  15. [
  16. 'param' => 'value',
  17. ]
  18. );
  19. var_dump(
  20. $this->getServerParams()
  21. );
  22. // [
  23. // 'param' => 'value',
  24. // ]

getUploadedFiles()

Returns an array with upload metadata in a normalized tree, with each leaf is an instance of Psr\Http\Message\UploadedFileInterface. These values can derive from the $_FILES superglobal or the message body during instantiation or they can be injected using withUploadedFiles(). If no data is present, an empty array will be returned.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest(
  4. 'GET',
  5. 'https://api.phalcon.io/companies/1',
  6. $_SERVER,
  7. 'php://input',
  8. [
  9. 'Content-Type' => 'application/json',
  10. ],
  11. $_COOKIE,
  12. $_GET,
  13. $_FILES
  14. );
  15. var_dump(
  16. $this->getUploadedFiles()
  17. );
  18. // [
  19. // 'my-form' => [
  20. // 'details' => [
  21. // 'invoice' => /* UploadedFileInterface instance */
  22. // ],
  23. // ],
  24. // ]

getUri()

Returns the Uri as a UriInterface object

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest(
  4. 'POST',
  5. 'https://api.phalcon.io/companies/1'
  6. );
  7. echo $request->getUri(); // UriInterface : https://api.phalcon.io/companies/1

Existence

hasHeader()

Checks if a header exists by the given case-insensitive name. Returns true if the header has been found, false otherwise

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $jwtToken = 'abc.def.ghi';
  4. $request = new ServerRequest(
  5. 'GET',
  6. 'https://api.phalcon.io/companies/1',
  7. $_SERVER,
  8. 'php://memory',
  9. [
  10. 'Authorization' => 'Bearer ' . $jwtToken,
  11. 'Content-Type' => [
  12. 'application/json',
  13. 'application/html',
  14. ],
  15. ]
  16. );
  17. echo $request->hasHeader('content-type'); // true

With

The Request object is immutable. However there are a number of methods that allow you to inject data into it. The returned object is a clone of the original one.

withAddedHeader()

Returns an instance with an additional header appended with the given value. Existing values for the specified header will be maintained. The new value(s) will be appended to the existing list. If the header did not exist previously, it will be added. Throws InvalidArgumentException for invalid header names or values. The header values can be a string or an array of strings.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $jwtToken = 'abc.def.ghi';
  4. $request = new ServerRequest(
  5. 'GET',
  6. 'https://api.phalcon.io/companies/1',
  7. $_SERVER,
  8. 'php://memory',
  9. [
  10. 'Authorization' => 'Bearer ' . $jwtToken,
  11. 'Content-Type' => [
  12. 'application/json',
  13. ],
  14. ]
  15. );
  16. var_dump(
  17. $request->getHeaders()
  18. );
  19. // [
  20. // 'Authorization' => 'Bearer abc.def.ghi',
  21. // 'Content-Type' => [
  22. // 'application/json',
  23. // ],
  24. // ]
  25. $clone = $request
  26. ->withAddedHeader(
  27. 'Content-Type',
  28. [
  29. 'application/html'
  30. ]
  31. );
  32. var_dump(
  33. $clone->getHeaders()
  34. );
  35. // [
  36. // 'Authorization' => 'Bearer abc.def.ghi',
  37. // 'Content-Type' => [
  38. // 'application/json',
  39. // 'application/html',
  40. // ],
  41. // ]

withAttribute()

Returns an instance with the specified derived request attribute. This method allows setting a single derived request attribute as described in getAttributes().

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest();
  4. $clone = $request
  5. ->withAttribute(
  6. 'attribute-name',
  7. 'attribute-value'
  8. );
  9. var_dump(
  10. $clone->getAttributes()
  11. );
  12. // [
  13. // 'attribute-name' => 'attribute-value',
  14. // ]

withBody()

Returns an instance with the specified message body which implements StreamInterface. Throws InvalidArgumentException when the body is not valid.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. use Phalcon\Http\Message\Stream;
  4. $fileName = dataFolder('/assets/stream/mit.txt');
  5. $stream = new Stream($fileName, 'rb');
  6. $request = new ServerRequest();
  7. $clone = $request->withBody($stream);
  8. echo $clone->getBody(); // '/assets/stream/mit.txt'

withCookieParams()

Returns an instance with the specified cookies. The data is not required to come from the $_COOKIE superglobal, but it must be compatible with the structure of $_COOKIE. Typically, this data will be injected at instantiation. This method does not update the related Cookie header of the request instance, nor related values in the server parameters.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest();
  4. $clone = $request
  5. ->withCookieParams(
  6. [
  7. 'cookie-name' => 'cookie-value',
  8. ]
  9. );
  10. var_dump(
  11. $clone->getCookieParams()
  12. );
  13. // [
  14. // 'cookie-name' => 'cookie-value',
  15. // ]

withHeader()

Returns an instance with the provided value replacing the specified header. While header names are case-insensitive, the casing of the header will be preserved by this function, and returned from getHeaders(). Throws InvalidArgumentException for invalid header names or values.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $jwtToken = 'abc.def.ghi';
  4. $request = new ServerRequest(
  5. 'GET',
  6. 'https://api.phalcon.io/companies/1',
  7. $_SERVER,
  8. 'php://memory',
  9. [
  10. 'Authorization' => 'Bearer ' . $jwtToken,
  11. ]
  12. );
  13. var_dump(
  14. $request->getHeaders()
  15. );
  16. // [
  17. // 'Authorization' => 'Bearer abc.def.ghi',
  18. // ]
  19. $clone = $request->withAddedHeader(
  20. 'Content-Type',
  21. [
  22. 'application/html',
  23. ]
  24. );
  25. var_dump(
  26. $clone->getHeaders()
  27. );
  28. // [
  29. // 'Authorization' => 'Bearer abc.def.ghi',
  30. // 'Content-Type' => [
  31. // 'application/html',
  32. // ],
  33. // ]

withMethod()

Return an instance with the provided HTTP method as a string. Throws InvalidArgumentException for invalid HTTP methods.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest('POST');
  4. echo $request->getMethod(); // POST
  5. $clone = $request->withMethod('GET');
  6. echo $clone->getMethod(); // GET

withParsedBody()

Returns an instance with the specified body parameters. If the request Content-Type is either application/x-www-form-urlencoded or multipart/form-data, and the request method is POST, this method should be used only to inject the contents of $_POST. The data is not required to come from $_POST, but wiill be the results of deserializing the request body content. Deserialization/parsing returns structured data, and, as such, this method only accepts arrays or objects, or a null value if nothing was available to parse.

As an example, if content negotiation determines that the request data is a JSON payload, this method could be used to create a request instance with the deserialized parameters. Throws InvalidArgumentException for unsupported argument types.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest();
  4. $clone = $request->withParsedBody(
  5. [
  6. 'one' => 'two',
  7. ]
  8. );
  9. echo $clone->getParsedBody();

withProtocolVersion()

Returns an instance with the specified HTTP protocol version (as string).

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest();
  4. echo $request->getProtocolVersion(); // '1.1'
  5. $clone = $request->withProtocolVersion('2.0');
  6. echo $clone->getProtocolVersion(); // '2.0'

withQueryParams()

Returns an instance with the specified query string arguments. These values remain immutable over the course of the incoming request. You can inject these parameters during instantiation, such as from PHP’s $_GET superglobal, or they can be derived from some other value such as the URI. In cases where the arguments are parsed from the URI, the data is compatible with what PHP’s parse_str() would return for purposes of how duplicate query parameters are handled, and how nested sets are handled.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest();
  4. $clone = $request->withQueryParams(
  5. [
  6. 'one' => 'two',
  7. ]
  8. );
  9. var_dump(
  10. $clone->getQueryParams()
  11. );
  12. // [
  13. // 'one' => 'two',
  14. // ]

withRequestTarget()

Returns an instance with the specific request-target.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest();
  4. echo $request->getRequestTarget(); // "/"
  5. $clone = $request->withRequestTarget('/test');
  6. echo $clone->getRequestTarget(); // '/test'

withUploadedFiles()

Creates a new instance with the specified uploaded files. It accepts an array tree of UploadedFileInterface instances. Throws InvalidArgumentException if an invalid structure is provided.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. use Phalcon\Http\Message\UploadedFile;
  4. $fileName = dataFolder('/assets/stream/mit.txt');
  5. $stream = new Stream($fileName, 'rb');
  6. $file = new UploadedFile(
  7. $stream,
  8. 1234,
  9. UPLOAD_ERR_OK,
  10. 'phalcon.txt'
  11. );
  12. $request = new ServerRequest();
  13. $clone = $request
  14. ->withUploadedFiles(
  15. [
  16. 'my-form' => [
  17. 'details' => [
  18. 'invoice' => $file,
  19. ]
  20. ]
  21. ]
  22. );
  23. var_dump(
  24. $this->getUploadedFiles()
  25. );
  26. // [
  27. // 'my-form' => [
  28. // 'details' => [
  29. // 'invoice' => /* UploadedFileInterface instance */
  30. // ],
  31. // ],
  32. // ]

withUri()

Returns an instance with the provided UriInterface URI. This method updates the Host header of the returned request by default if the URI contains a host component. If the URI does not contain a host component, any pre-existing Host header will be carried over to the returned request.

You can opt-in to preserving the original state of the Host header by setting $preserveHost to true. When $preserveHost is set to true, this method interacts with the Host header in the following ways:

  • If the Host header is missing or empty, and the new URI contains a host component, this method will update the Host header in the returned request.
  • If the Host header is missing or empty, and the new URI does not contain a host component, this method will not update the Host header in the returned request.
  • If a Host header is present and non-empty, this method will not update the Host header in the returned request.
  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $query = 'https://phalcon.io';
  4. $uri = new Uri($query);
  5. $request = new ServerRequest();
  6. $clone = $request->withUri($uri);
  7. echo $clone->getRequestTarget(); // 'https://phalcon.io'

withoutAttribute()

Returns an instance that removes the specified derived request attribute. This method allows removing a single derived request attribute as described in getAttributes().

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $request = new ServerRequest();
  4. $clone = $request
  5. ->withAttribute('one', 'two')
  6. ->withAttribute('three', 'four')
  7. ;
  8. var_dump(
  9. $clone->getAttributes()
  10. );
  11. // [
  12. // 'one' => 'two',
  13. // 'three' => 'four',
  14. // ]
  15. $newClone = $request
  16. ->withoutAttribute('one')
  17. ;
  18. var_dump(
  19. $newClone->getAttributes()
  20. );
  21. // [
  22. // 'three' => 'four',
  23. // ]

withoutHeader()

Return an instance without the specified header.

  1. <?php
  2. use Phalcon\Http\Message\ServerRequest;
  3. $jwtToken = 'abc.def.ghi';
  4. $request = new ServerRequest(
  5. 'GET',
  6. 'https://api.phalcon.io/companies/1',
  7. $_SERVER,
  8. 'php://memory',
  9. [
  10. 'Authorization' => 'Bearer ' . $jwtToken,
  11. 'Content-Type' => [
  12. 'application/json',
  13. ],
  14. ]
  15. );
  16. var_dump(
  17. $request->getHeaders()
  18. );
  19. // [
  20. // 'Authorization' => 'Bearer abc.def.ghi',
  21. // 'Content-Type' => [
  22. // 'application/json',
  23. // ],
  24. // ]
  25. $clone = $request->withoutHeader('Content-Type');
  26. var_dump(
  27. $clone->getHeaders()
  28. );
  29. // [
  30. // 'Authorization' => 'Bearer abc.def.ghi',
  31. // ]