Skip to content

Phalcon http

NOTE

All classes are prefixed with Phalcon

Http\Cookie

Class Source on GitHub

Provide OO wrappers to manage a HTTP cookie.

Uses Phalcon\Di\AbstractInjectionAware · Phalcon\Di\DiInterface · Phalcon\Encryption\Crypt\CryptInterface · Phalcon\Filter\FilterInterface · Phalcon\Http\Cookie\CookieInterface · Phalcon\Http\Cookie\Exception · Phalcon\Http\Cookie\Exceptions\CookieKeyTooShort · Phalcon\Http\Cookie\Exceptions\CryptInterfaceRequired · Phalcon\Http\Cookie\Exceptions\CryptServiceUnavailable · Phalcon\Http\Cookie\Exceptions\FilterServiceUnavailable · Phalcon\Http\Response\Exception · Phalcon\Http\Traits\EncryptionAwareTrait · Phalcon\Session\ManagerInterface · Phalcon\Traits\Support\Helper\Arr\GetTrait · Stringable

Method Summary

public __construct(string $name,mixed $value = null,int $expire = 0,string $path = "/",bool $secure = false,string $domain = "",bool $httpOnly = false,array $options = []) Phalcon\Http\Cookie constructor. public string __toString() Magic __toString method converts the cookie's value to string public void delete() Deletes the cookie by setting an expiration time in the past public string getDomain() Returns the domain that the cookie is available to public int getExpiration() Returns the current expiration time public bool getHttpOnly() Returns if the cookie is accessible only through the HTTP protocol public string getName() Returns the current cookie's name public array getOptions() Returns the current cookie's options public string getPath() Returns the current cookie's path public bool getSecure() Returns whether the cookie must only be sent when the connection is public mixed getValue(mixed $filters = null,mixed $defaultValue = null) Returns the cookie's value. public CookieInterface restore() Reads the cookie-related info from the SESSION to restore the cookie as public CookieInterface send() Sends the cookie to the HTTP client. public CookieInterface setDomain( string $domain ) Sets the domain that the cookie is available to public CookieInterface setExpiration( int $expire ) Sets the cookie's expiration time public CookieInterface setHttpOnly( bool $httpOnly ) Sets if the cookie is accessible only through the HTTP protocol public CookieInterface setOptions( array $options ) Sets the cookie's options public CookieInterface setPath( string $path ) Sets the cookie's path public CookieInterface setSecure( bool $secure ) Sets if the cookie must only be sent when the connection is secure public CookieInterface setSignKey( string|null $signKey = null ) Sets the cookie's sign key. public CookieInterface setValue( mixed $value ) Sets the cookie's value public CookieInterface useEncryption( bool $useEncryption ) Sets if the cookie must be encrypted/decrypted automatically protected void assertSignKeyIsLongEnough( string $signKey ) Assert the cookie's key is enough long.

Constants

string COOKIE_PREFIX = "_PHCOOKIE_"

Properties

protected string $domain = ""
protected int $expire = 0
protected FilterInterface|null $filter = null
protected bool $httpOnly = false
protected bool $isRead = false
protected bool $isRestored = false
protected string $name
protected array $options = []
protected string $path = "/"
protected bool $secure = false
protected string|null $signKey = null The cookie's sign key.
protected mixed|null $value = null

Methods

Public · 22

__construct()

public function __construct(
    string $name,
    mixed $value = null,
    int $expire = 0,
    string $path = "/",
    bool $secure = false,
    string $domain = "",
    bool $httpOnly = false,
    array $options = []
);

Phalcon\Http\Cookie constructor.

__toString()

public function __toString(): string;

Magic __toString method converts the cookie's value to string

delete()

public function delete(): void;

Deletes the cookie by setting an expiration time in the past

getDomain()

public function getDomain(): string;

Returns the domain that the cookie is available to

getExpiration()

public function getExpiration(): int;

Returns the current expiration time

getHttpOnly()

public function getHttpOnly(): bool;

Returns if the cookie is accessible only through the HTTP protocol

getName()

public function getName(): string;

Returns the current cookie's name

getOptions()

public function getOptions(): array;

Returns the current cookie's options

getPath()

public function getPath(): string;

Returns the current cookie's path

getSecure()

public function getSecure(): bool;

Returns whether the cookie must only be sent when the connection is secure (HTTPS)

getValue()

public function getValue(
    mixed $filters = null,
    mixed $defaultValue = null
): mixed;

Returns the cookie's value.

restore()

public function restore(): CookieInterface;

Reads the cookie-related info from the SESSION to restore the cookie as it was set.

This method is automatically called internally so normally you don't need to call it.

send()

public function send(): CookieInterface;

Sends the cookie to the HTTP client.

Stores the cookie definition in session.

setDomain()

public function setDomain( string $domain ): CookieInterface;

Sets the domain that the cookie is available to

setExpiration()

public function setExpiration( int $expire ): CookieInterface;

Sets the cookie's expiration time

setHttpOnly()

public function setHttpOnly( bool $httpOnly ): CookieInterface;

Sets if the cookie is accessible only through the HTTP protocol

setOptions()

public function setOptions( array $options ): CookieInterface;

Sets the cookie's options

setPath()

public function setPath( string $path ): CookieInterface;

Sets the cookie's path

setSecure()

public function setSecure( bool $secure ): CookieInterface;

Sets if the cookie must only be sent when the connection is secure (HTTPS)

setSignKey()

public function setSignKey( string|null $signKey = null ): CookieInterface;

Sets the cookie's sign key.

The `$signKey' MUST be at least 32 characters long and generated using a cryptographically secure pseudo random generator.

Use NULL to disable cookie signing.

setValue()

public function setValue( mixed $value ): CookieInterface;

Sets the cookie's value

useEncryption()

public function useEncryption( bool $useEncryption ): CookieInterface;

Sets if the cookie must be encrypted/decrypted automatically

Protected · 1

assertSignKeyIsLongEnough()

protected function assertSignKeyIsLongEnough( string $signKey ): void;

Assert the cookie's key is enough long.

Http\Cookie\CookieInterface

Interface Source on GitHub

Interface for Phalcon\Http\Cookie

  • Phalcon\Http\Cookie\CookieInterface

Method Summary

public void delete() Deletes the cookie public string getDomain() Returns the domain that the cookie is available to public int getExpiration() Returns the current expiration time public bool getHttpOnly() Returns if the cookie is accessible only through the HTTP protocol public string getName() Returns the current cookie's name public array getOptions() Returns the current cookie's options public string getPath() Returns the current cookie's path public bool getSecure() Returns whether the cookie must only be sent when the connection is public mixed getValue(mixed $filters = null,mixed $defaultValue = null) Returns the cookie's value. public bool isUsingEncryption() Check if the cookie is using implicit encryption public CookieInterface send() Sends the cookie to the HTTP client public CookieInterface setDomain( string $domain ) Sets the domain that the cookie is available to public CookieInterface setExpiration( int $expire ) Sets the cookie's expiration time public CookieInterface setHttpOnly( bool $httpOnly ) Sets if the cookie is accessible only through the HTTP protocol public CookieInterface setOptions( array $options ) Sets the cookie's options public CookieInterface setPath( string $path ) Sets the cookie's expiration time public CookieInterface setSecure( bool $secure ) Sets if the cookie must only be sent when the connection is secure public CookieInterface setValue( mixed $value ) Sets the cookie's value public CookieInterface useEncryption( bool $useEncryption ) Sets if the cookie must be encrypted/decrypted automatically

Methods

Public · 19

delete()

public function delete(): void;

Deletes the cookie

getDomain()

public function getDomain(): string;

Returns the domain that the cookie is available to

getExpiration()

public function getExpiration(): int;

Returns the current expiration time

getHttpOnly()

public function getHttpOnly(): bool;

Returns if the cookie is accessible only through the HTTP protocol

getName()

public function getName(): string;

Returns the current cookie's name

getOptions()

public function getOptions(): array;

Returns the current cookie's options

getPath()

public function getPath(): string;

Returns the current cookie's path

getSecure()

public function getSecure(): bool;

Returns whether the cookie must only be sent when the connection is secure (HTTPS)

getValue()

public function getValue(
    mixed $filters = null,
    mixed $defaultValue = null
): mixed;

Returns the cookie's value.

isUsingEncryption()

public function isUsingEncryption(): bool;

Check if the cookie is using implicit encryption

send()

public function send(): CookieInterface;

Sends the cookie to the HTTP client

setDomain()

public function setDomain( string $domain ): CookieInterface;

Sets the domain that the cookie is available to

setExpiration()

public function setExpiration( int $expire ): CookieInterface;

Sets the cookie's expiration time

setHttpOnly()

public function setHttpOnly( bool $httpOnly ): CookieInterface;

Sets if the cookie is accessible only through the HTTP protocol

setOptions()

public function setOptions( array $options ): CookieInterface;

Sets the cookie's options

setPath()

public function setPath( string $path ): CookieInterface;

Sets the cookie's expiration time

setSecure()

public function setSecure( bool $secure ): CookieInterface;

Sets if the cookie must only be sent when the connection is secure (HTTPS)

setValue()

public function setValue( mixed $value ): CookieInterface;

Sets the cookie's value

useEncryption()

public function useEncryption( bool $useEncryption ): CookieInterface;

Sets if the cookie must be encrypted/decrypted automatically

Http\Cookie\Exception

Class Source on GitHub

Phalcon\Http\Cookie\Exception

Exceptions thrown in Phalcon\Http\Cookie will use this class.

Http\Cookie\Exceptions\CookieKeyTooShort

Class Source on GitHub

Uses Phalcon\Http\Cookie\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( int $length );

Http\Cookie\Exceptions\CryptInterfaceRequired

Class Source on GitHub

Uses Phalcon\Http\Cookie\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Http\Cookie\Exceptions\CryptServiceUnavailable

Class Source on GitHub

Uses Phalcon\Http\Cookie\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Http\Cookie\Exceptions\FilterServiceUnavailable

Class Source on GitHub

Uses Phalcon\Http\Cookie\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Http\Enums\HttpStatusEnum

Class Source on GitHub

Status Phrases trait

  • Phalcon\Http\Enums\HttpStatusEnum

Method Summary

Constants

int Accepted = 202
int AlreadyReported = 208
int BadGateway = 502
int BadRequest = 400
int Conflict = 409
int Continue = 100
int Created = 201
int EarlyHints = 103
int ExpectationFailed = 417
int FailedDependency = 424
int Forbidden = 403
int Found = 302
int GatewayTimeout = 504
int Gone = 410
int ImATeapot = 418
int ImUsed = 226
int InsufficientStorage = 507
int InternalServerError = 500
int LengthRequired = 411
int Locked = 423
int LoopDetected = 508
int MethodNotAllowed = 405
int MisdirectedRequest = 421
int MovedPermanently = 301
int MultiStatus = 207
int MultipleChoices = 300
int NetworkAuthenticationRequired = 511
int NoContent = 204
int NonAuthoritativeInformation = 203
int NotAcceptable = 406
int NotExtended = 510
int NotFound = 404
int NotImplemented = 501
int NotModified = 304
int OK = 200
int PartialContent = 206
int PayloadTooLarge = 413
int PaymentRequired = 402
int PermanentRedirect = 308
int PreconditionFailed = 412
int PreconditionRequired = 428
int Processing = 102
int ProxyAuthenticationRequired = 407
int RangeNotSatisfiable = 416
int RequestHeaderFieldsTooLarge = 431
int RequestTimeout = 408
int Reserved = 306
int ResetContent = 205
int SeeOther = 303
int ServiceUnavailable = 503
int SwitchingProtocols = 101
int TemporaryRedirect = 307
int TooEarly = 425
int TooManyRequests = 429
int Unauthorized = 401
int UnavailableForLegalReasons = 451
int UnprocessableEntity = 422
int UnsupportedMediaType = 415
int UpgradeRequired = 426
int UriTooLong = 414
int UseProxy = 305
int VariantAlsoNegotiates = 506
int VersionNotSupported = 505

Methods

Public · 1

text()

public function text(): string;

Http\Message\AbstractCommon

Abstract Source on GitHub

Common methods

Uses Phalcon\Http\Message\Exception\InvalidArgumentException

Method Summary

Methods

Protected · 2

checkStringParameter()

final protected function checkStringParameter( mixed $element ): void;

Checks the element passed if it is a string

cloneInstance()

final protected function cloneInstance(
    mixed $element,
    string $property
);

Returns a new instance having set the parameter

Http\Message\AbstractMessage

Abstract Source on GitHub

Message methods

Uses Phalcon\Http\Message\Exception\InvalidArgumentException · Phalcon\Http\Message\Interfaces\MessageInterface · Phalcon\Http\Message\Interfaces\ResponseStatusCodeInterface · Phalcon\Http\Message\Interfaces\StreamInterface

Method Summary

Properties

protected StreamInterface $body Gets the body of the message.
protected Headers $headers
protected string $protocolVersion = "1.1" Retrieves the HTTP protocol version as a string. The string MUST contain only the HTTP version number (e.g., '1.1', '1.0').

Methods

Public · 11

getBody()

public function getBody(): StreamInterface;

Return the body of the stream

getHeader()

public function getHeader( string $name ): array;

Retrieves a message header value by the given case-insensitive name.

This method returns an array of all the header values of the given case-insensitive header name.

If the header does not appear in the message, this method MUST return an empty array.

getHeaderLine()

public function getHeaderLine( string $name ): string;

Retrieves a comma-separated string of the values for a single header.

This method returns all the header values of the given case-insensitive header name as a string concatenated together using a comma.

NOTE: Not all header values may be appropriately represented using comma concatenation. For such headers, use getHeader() instead and supply your own delimiter when concatenating.

If the header does not appear in the message, this method MUST return an empty string.

getHeaders()

public function getHeaders(): array;

Retrieves all 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.

// Represent the headers as a string
foreach ($message->getHeaders() as $name => $values) {
    echo $name . ': ' . implode(', ', $values);
}

// Emit headers iteratively:
foreach ($message->getHeaders() as $name => $values) {
    foreach ($values as $value) {
        header(sprintf('%s: %s', $name, $value), false);
    }
}

While header names are not case-sensitive, getHeaders() will preserve the exact case in which headers were originally specified.

getProtocolVersion()

public function getProtocolVersion(): string;

Returns the protocol version

hasHeader()

public function hasHeader( string $name ): bool;

Checks if a header exists by the given case-insensitive name.

withAddedHeader()

public function withAddedHeader(
    string $name,
    mixed $value
): MessageInterface;

Return an instance with the specified 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.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new header and/or value.

withBody()

public function withBody( StreamInterface $body ): MessageInterface;

Return an instance with the specified message body.

The body MUST be a StreamInterface object.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return a new instance that has the new body stream.

withHeader()

public function withHeader(
    string $name,
    mixed $value
): MessageInterface;

Return 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().

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new and/or updated header and value.

withProtocolVersion()

public function withProtocolVersion( string $version ): MessageInterface;

Return an instance with the specified HTTP protocol version.

The version string MUST contain only the HTTP version number (e.g., '1.1', '1.0').

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new protocol version.

withoutHeader()

public function withoutHeader( string $name ): MessageInterface;

Return an instance without the specified header.

Header resolution MUST be done without case-sensitivity.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that removes the named header.

Protected · 2

processBody()

final protected function processBody(
    mixed $body = "php://memory",
    string $mode = "r+b"
): StreamInterface;

Set a valid stream

processProtocol()

final protected function processProtocol( string $protocol = "" ): string;

Checks the protocol

Http\Message\AbstractRequest

Abstract Source on GitHub

Request methods

@property string $method @property string|null $requestTarget @property UriInterface $uri

Uses Phalcon\Http\Message\Exception\InvalidArgumentException · Phalcon\Http\Message\Interfaces\RequestInterface · Phalcon\Http\Message\Interfaces\RequestMethodInterface · Phalcon\Http\Message\Interfaces\UriInterface

Method Summary

Properties

protected string $method = self::METHOD_GET Retrieves the HTTP method of the request.
protected string|null $requestTarget = null The request-target, if it has been provided or calculated.
protected UriInterface $uri Retrieves the URI instance. This method MUST return a UriInterface instance. @see https://tools.ietf.org/html/rfc3986#section-4.3

Methods

Public · 6

getMethod()

public function getMethod(): string;

getRequestTarget()

public function getRequestTarget(): string;

Retrieves the message's request target.

Retrieves 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() below).

getUri()

public function getUri(): UriInterface;

Returns the Uri object

withMethod()

public function withMethod( string $method ): RequestInterface;

Return an instance with the provided HTTP method.

While HTTP method names are typically all uppercase characters, HTTP method names are case-sensitive and thus implementations SHOULD NOT modify the given string.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the changed request method.

withRequestTarget()

public function withRequestTarget( string|null $requestTarget ): RequestInterface;

Return an instance with the specific request-target.

If the request needs a non-origin-form request-target - e.g., for specifying an absolute-form, authority-form, or asterisk-form - this method may be used to create an instance with the specified request-target, verbatim.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the changed request target.

@see https://tools.ietf.org/html/rfc7230#section-5.3 (for the various request-target forms allowed in request messages)

withUri()

public function withUri(
    UriInterface $uri,
    bool $preserveHost = false
): RequestInterface;

Returns an instance with the provided URI.

This method MUST update 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 MUST 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 MUST 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 MUST NOT update the Host header in the returned request.
  • If a Host header is present and non-empty, this method MUST NOT update the Host header in the returned request.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new UriInterface instance.

@see https://tools.ietf.org/html/rfc3986#section-4.3

Protected · 2

processMethod()

final protected function processMethod( string $method = "" ): string;

Check the method

processUri()

final protected function processUri( mixed $uri ): UriInterface;

Sets a valid Uri

Http\Message\Exception\InvalidArgumentException

Class Source on GitHub

  • \InvalidArgumentException
    • Phalcon\Http\Message\Exception\InvalidArgumentException - implements \Throwable

Uses Throwable

Http\Message\Exception\RuntimeException

Class Source on GitHub

  • \RuntimeException
    • Phalcon\Http\Message\Exception\RuntimeException - implements \Throwable

Uses Throwable

Http\Message\Factories\RequestFactory

Final Source on GitHub

Factory for Request objects

Uses Phalcon\Http\Message\Interfaces\RequestFactoryInterface · Phalcon\Http\Message\Interfaces\RequestInterface · Phalcon\Http\Message\Interfaces\UriInterface · Phalcon\Http\Message\Request

Method Summary

Methods

Public · 1

createRequest()

public function createRequest(
    string $method,
    mixed $uri
): RequestInterface;

Create a new request.

Http\Message\Factories\ResponseFactory

Final Source on GitHub

Factory for Response objects

Uses Phalcon\Http\Message\Interfaces\ResponseFactoryInterface · Phalcon\Http\Message\Interfaces\ResponseInterface · Phalcon\Http\Message\Response

Method Summary

Methods

Public · 1

createResponse()

public function createResponse(
    int $code = 200,
    string $reasonPhrase = ""
): ResponseInterface;

Create a new response.

Http\Message\Factories\ServerRequestFactory

Class Source on GitHub

Factory for ServerRequest objects

Uses Phalcon\Http\Message\Exception\InvalidArgumentException · Phalcon\Http\Message\Interfaces\RequestMethodInterface · Phalcon\Http\Message\Interfaces\ServerRequestFactoryInterface · Phalcon\Http\Message\Interfaces\ServerRequestInterface · Phalcon\Http\Message\Interfaces\UploadedFileInterface · Phalcon\Http\Message\Interfaces\UriInterface · Phalcon\Http\Message\ServerRequest · Phalcon\Http\Message\UploadedFile · Phalcon\Http\Message\Uri · Phalcon\Support\Collection · Phalcon\Support\Collection\CollectionInterface

Method Summary

Methods

Public · 2

createServerRequest()

public function createServerRequest(
    string $method,
    mixed $uri,
    array $serverParams = []
): ServerRequestInterface;

Create a new server request.

Note that server-params are taken precisely as given - no parsing/processing of the given values is performed, and, in particular, no attempt is made to determine the HTTP method or URI, which must be provided explicitly.

load()

public function load(
    array|null $server = null,
    array|null $get = null,
    array|null $post = null,
    array|null $cookies = null,
    array|null $files = null
): ServerRequest;

Create a request from the supplied superglobal values.

If any argument is not supplied, the corresponding superglobal value will be used.

Protected · 1

getHeaders()

protected function getHeaders();

Returns the apache_request_headers if it exists

Http\Message\Factories\StreamFactory

Final Source on GitHub

Factory for Stream objects

Uses Phalcon\Http\Message\Exception\InvalidArgumentException · Phalcon\Http\Message\Interfaces\StreamFactoryInterface · Phalcon\Http\Message\Interfaces\StreamInterface · Phalcon\Http\Message\Stream · Phalcon\Traits\Php\FileTrait

Method Summary

Methods

Public · 3

createStream()

public function createStream( string $content = "" ): StreamInterface;

Create a new stream from a string.

The stream SHOULD be created with a temporary resource.

createStreamFromFile()

public function createStreamFromFile(
    string $filename,
    string $mode = "r+b"
): StreamInterface;

Create a stream from an existing file.

The file MUST be opened using the given mode, which may be any mode supported by the fopen function.

The $filename MAY be any string supported by fopen().

createStreamFromResource()

public function createStreamFromResource( mixed $phpResource ): StreamInterface;

Create a new stream from an existing resource.

The stream MUST be readable and may be writable.

Http\Message\Factories\UploadedFileFactory

Final Source on GitHub

Factory for UploadedFile objects

Uses Phalcon\Http\Message\Exception\InvalidArgumentException · Phalcon\Http\Message\Interfaces\StreamInterface · Phalcon\Http\Message\Interfaces\UploadedFileFactoryInterface · Phalcon\Http\Message\Interfaces\UploadedFileInterface · Phalcon\Http\Message\UploadedFile

Method Summary

Methods

Public · 1

createUploadedFile()

public function createUploadedFile(
    StreamInterface $stream,
    int|null $size = null,
    int $error = 0,
    string|null $clientFilename = null,
    string|null $clientMediaType = null
): UploadedFileInterface;

Create a new uploaded file.

If a size is not provided it will be determined by checking the size of the stream.

@link httsp://php.net/manual/features.file-upload.post-method.php @link https://php.net/manual/features.file-upload.errors.php

Http\Message\Factories\UriFactory

Final Source on GitHub

Factory for Uri objects

Uses Phalcon\Http\Message\Interfaces\UriFactoryInterface · Phalcon\Http\Message\Interfaces\UriInterface · Phalcon\Http\Message\Uri

Method Summary

Methods

Public · 1

createUri()

public function createUri( string $uri = "" ): UriInterface;

Returns a Uri object

Http\Message\Headers

Class Source on GitHub

Message methods

Uses Phalcon\Http\Message\Exception\InvalidArgumentException · Phalcon\Http\Message\Interfaces\UriInterface · Phalcon\Support\Collection

Method Summary

Methods

Public · 6

checkHeaderHost()

final public function checkHeaderHost(
    Headers $collection,
    UriInterface|null $uri = null
): Headers;

Ensure Host is the first header.

@see: https://tools.ietf.org/html/rfc7230#section-5.4

checkHeaderName()

final public function checkHeaderName( string $name ): void;

Check the name of the header. Throw exception if not valid

@see https://tools.ietf.org/html/rfc7230#section-3.2

checkHeaderValue()

final public function checkHeaderValue( mixed $value ): void;

Validates a header value

Most HTTP header field values are defined using common syntax components (token, quoted-string, and comment) separated by whitespace or specific delimiting characters. Delimiters are chosen from the set of US-ASCII visual characters not allowed in a token (DQUOTE and '(),/:;<=>?@[]{}').

token          = 1*tchar

tchar          = '!' / '#' / '$' / '%' / '&' / ''' / '*'
               / '+' / '-' / '.' / '^' / '_' / '`' / '|' / '~'
               / DIGIT / ALPHA
               ; any VCHAR, except delimiters

A string of text is parsed as a single value if it is quoted using double-quote marks.

quoted-string  = DQUOTE *( qdtext / quoted-pair ) DQUOTE
qdtext         = HTAB / SP /%x21 / %x23-5B / %x5D-7E / obs-text
obs-text       = %x80-FF

Comments can be included in some HTTP header fields by surrounding the comment text with parentheses. Comments are only allowed in fields containing 'comment' as part of their field value definition.

comment        = '(' *( ctext / quoted-pair / comment ) ')'
ctext          = HTAB / SP / %x21-27 / %x2A-5B / %x5D-7E / obs-text

The backslash octet ('\') can be used as a single-octet quoting mechanism within quoted-string and comment constructs. Recipients that process the value of a quoted-string MUST handle a quoted-pair as if it were replaced by the octet following the backslash.

quoted-pair    = '\' ( HTAB / SP / VCHAR / obs-text )

A sender SHOULD NOT generate a quoted-pair in a quoted-string except where necessary to quote DQUOTE and backslash octets occurring within that string. A sender SHOULD NOT generate a quoted-pair in a comment except where necessary to quote parentheses ['(' and ')'] and backslash octets occurring within that comment.

@see https://tools.ietf.org/html/rfc7230#section-3.2.6

getHeaderValue()

final public function getHeaderValue( mixed $values ): array;

Returns the header values checked for validity

populateHeaders()

final public function populateHeaders( array $headers ): Headers;

Populates the header collection

processHeaders()

final public function processHeaders(
    mixed $headers,
    UriInterface|null $uri = null
): Headers;

Sets the headers

Protected · 1

setData()

protected function setData(
    string $element,
    mixed $value
): void;

Internal method to set data

Http\Message\Interfaces\MessageInterface

Interface Source on GitHub

HTTP messages consist of requests from a client to a server and responses from a server to a client. This interface defines the methods common to each.

Messages are considered immutable; all methods that might change state MUST be implemented such that they retain the internal state of the current message and return an instance that contains the changed state.

@link https://www.ietf.org/rfc/rfc7230.txt @link https://www.ietf.org/rfc/rfc7231.txt

Uses Phalcon\Http\Message\Exception\InvalidArgumentException

Method Summary

Methods

Public · 11

getBody()

public function getBody(): StreamInterface;

Gets the body of the message.

getHeader()

public function getHeader( string $name ): array;

Retrieves a message header value by the given case-insensitive name.

This method returns an array of all the header values of the given case-insensitive header name.

If the header does not appear in the message, this method MUST return an empty array.

getHeaderLine()

public function getHeaderLine( string $name ): string;

Retrieves a comma-separated string of the values for a single header.

This method returns all of the header values of the given case-insensitive header name as a string concatenated together using a comma.

NOTE: Not all header values may be appropriately represented using comma concatenation. For such headers, use getHeader() instead and supply your own delimiter when concatenating.

If the header does not appear in the message, this method MUST return an empty string.

getHeaders()

public function getHeaders(): array;

Retrieves all 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.

// Represent the headers as a string
foreach ($message->getHeaders() as $name => $values) {
    echo $name . ": " . implode(", ", $values);
}

// Emit headers iteratively:
foreach ($message->getHeaders() as $name => $values) {
    foreach ($values as $value) {
        header(sprintf('%s: %s', $name, $value), false);
    }
}

While header names are not case-sensitive, getHeaders() will preserve the exact case in which headers were originally specified.

getProtocolVersion()

public function getProtocolVersion(): string;

Retrieves the HTTP protocol version as a string.

The string MUST contain only the HTTP version number (e.g., "1.1", "1.0").

hasHeader()

public function hasHeader( string $name ): bool;

Checks if a header exists by the given case-insensitive name.

withAddedHeader()

public function withAddedHeader(
    string $name,
    mixed $value
): MessageInterface;

Return an instance with the specified 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.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new header and/or value.

withBody()

public function withBody( StreamInterface $body ): MessageInterface;

Return an instance with the specified message body.

The body MUST be a StreamInterface object.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return a new instance that has the new body stream.

withHeader()

public function withHeader(
    string $name,
    mixed $value
): MessageInterface;

Return 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().

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new and/or updated header and value.

withProtocolVersion()

public function withProtocolVersion( string $version ): MessageInterface;

Return an instance with the specified HTTP protocol version.

The version string MUST contain only the HTTP version number (e.g., "1.1", "1.0").

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new protocol version.

withoutHeader()

public function withoutHeader( string $name ): MessageInterface;

Return an instance without the specified header.

Header resolution MUST be done without case-sensitivity.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that removes the named header.

Http\Message\Interfaces\RequestFactoryInterface

Interface Source on GitHub

  • Phalcon\Http\Message\Interfaces\RequestFactoryInterface

Method Summary

Methods

Public · 1

createRequest()

public function createRequest(
    string $method,
    mixed $uri
): RequestInterface;

Create a new request.

Http\Message\Interfaces\RequestInterface

Interface Source on GitHub

Representation of an outgoing, client-side request.

Per the HTTP specification, this interface includes properties for each of the following:

  • Protocol version
  • HTTP method
  • URI
  • Headers
  • Message body

During construction, implementations MUST attempt to set the Host header from a provided URI if no Host header is provided.

Requests are considered immutable; all methods that might change state MUST be implemented such that they retain the internal state of the current message and return an instance that contains the changed state.

Uses Phalcon\Http\Message\Exception\InvalidArgumentException

Method Summary

Methods

Public · 6

getMethod()

public function getMethod(): string;

Retrieves the HTTP method of the request.

getRequestTarget()

public function getRequestTarget(): string;

Retrieves the message's request target.

Retrieves 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() below).

If no URI is available, and no request-target has been specifically provided, this method MUST return the string "/".

getUri()

public function getUri(): UriInterface;

Retrieves the URI instance.

This method MUST return a UriInterface instance.

@link https://tools.ietf.org/html/rfc3986#section-4.3

withMethod()

public function withMethod( string $method ): RequestInterface;

Return an instance with the provided HTTP method.

While HTTP method names are typically all uppercase characters, HTTP method names are case-sensitive and thus implementations SHOULD NOT modify the given string.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the changed request method.

withRequestTarget()

public function withRequestTarget( string|null $requestTarget ): RequestInterface;

Return an instance with the specific request-target.

If the request needs a non-origin-form request-target - e.g., for specifying an absolute-form, authority-form, or asterisk-form - this method may be used to create an instance with the specified request-target, verbatim.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the changed request target.

@link https://tools.ietf.org/html/rfc7230#section-5.3 (for the various request-target forms allowed in request messages)

withUri()

public function withUri(
    UriInterface $uri,
    bool $preserveHost = false
): RequestInterface;

Returns an instance with the provided URI.

This method MUST update 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 MUST 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 MUST 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 MUST NOT update the Host header in the returned request.
  • If a Host header is present and non-empty, this method MUST NOT update the Host header in the returned request.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new UriInterface instance.

@link https://tools.ietf.org/html/rfc3986#section-4.3

Http\Message\Interfaces\RequestMethodInterface

Interface Source on GitHub

Interface for Request methods

Implementation of this file has been influenced by PHP FIG

@link https://github.com/php-fig/http-message-util/ @license https://github.com/php-fig/http-message-util/blob/master/LICENSE

  • Phalcon\Http\Message\Interfaces\RequestMethodInterface

Constants

string METHOD_CONNECT = "CONNECT"
string METHOD_DELETE = "DELETE"
string METHOD_GET = "GET"
string METHOD_HEAD = "HEAD"
string METHOD_OPTIONS = "OPTIONS"
string METHOD_PATCH = "PATCH"
string METHOD_POST = "POST"
string METHOD_PURGE = "PURGE"
string METHOD_PUT = "PUT"
string METHOD_TRACE = "TRACE"

Http\Message\Interfaces\ResponseFactoryInterface

Interface Source on GitHub

  • Phalcon\Http\Message\Interfaces\ResponseFactoryInterface

Method Summary

Methods

Public · 1

createResponse()

public function createResponse(
    int $code = 200,
    string $reasonPhrase = ""
): ResponseInterface;

Create a new response.

Http\Message\Interfaces\ResponseInterface

Interface Source on GitHub

Representation of an outgoing, server-side response.

Per the HTTP specification, this interface includes properties for each of the following:

  • Protocol version
  • Status code and reason phrase
  • Headers
  • Message body

Responses are considered immutable; all methods that might change state MUST be implemented such that they retain the internal state of the current message and return an instance that contains the changed state.

Uses Phalcon\Http\Message\Exception\InvalidArgumentException

Method Summary

Methods

Public · 3

getReasonPhrase()

public function getReasonPhrase(): string;

Gets the response reason phrase associated with the status code.

Because a reason phrase is not a required element in a response status line, the reason phrase value MAY be null. Implementations MAY choose to return the default RFC 7231 recommended reason phrase (or those listed in the IANA HTTP Status Code Registry) for the response's status code.

@link https://tools.ietf.org/html/rfc7231#section-6 @link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

getStatusCode()

public function getStatusCode(): int;

Gets the response status code.

The status code is a 3-digit integer result code of the server's attempt to understand and satisfy the request.

withStatus()

public function withStatus(
    int $code,
    string $reasonPhrase = ""
): ResponseInterface;

Return an instance with the specified status code and, optionally, reason phrase.

If no reason phrase is specified, implementations MAY choose to default to the RFC 7231 or IANA recommended reason phrase for the response's status code.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated status and reason phrase.

@link https://tools.ietf.org/html/rfc7231#section-6 @link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

Http\Message\Interfaces\ResponseStatusCodeInterface

Interface Source on GitHub

Interface for Request methods

Implementation of this file has been influenced by PHP FIG

@link https://github.com/php-fig/http-message-util/ @license https://github.com/php-fig/http-message-util/blob/master/LICENSE

Defines constants for common HTTP status code.

@see https://tools.ietf.org/html/rfc2295#section-8.1 @see https://tools.ietf.org/html/rfc2324#section-2.3 @see https://tools.ietf.org/html/rfc2518#section-9.7 @see https://tools.ietf.org/html/rfc2774#section-7 @see https://tools.ietf.org/html/rfc3229#section-10.4 @see https://tools.ietf.org/html/rfc4918#section-11 @see https://tools.ietf.org/html/rfc5842#section-7.1 @see https://tools.ietf.org/html/rfc5842#section-7.2 @see https://tools.ietf.org/html/rfc6585#section-3 @see https://tools.ietf.org/html/rfc6585#section-4 @see https://tools.ietf.org/html/rfc6585#section-5 @see https://tools.ietf.org/html/rfc6585#section-6 @see https://tools.ietf.org/html/rfc7231#section-6 @see https://tools.ietf.org/html/rfc7238#section-3 @see https://tools.ietf.org/html/rfc7725#section-3 @see https://tools.ietf.org/html/rfc7540#section-9.1.2 @see https://tools.ietf.org/html/rfc8297#section-2 @see https://tools.ietf.org/html/rfc8470#section-7

Constants

int STATUS_ACCEPTED = 202
int STATUS_ALREADY_REPORTED = 208
int STATUS_BAD_GATEWAY = 502
int STATUS_BAD_REQUEST = 400
int STATUS_BANDWIDTH_LIMIT_EXCEEDED = 509
int STATUS_BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS = 450
int STATUS_CLIENT_CLOSED_REQUEST = 499
int STATUS_CONFLICT = 409
int STATUS_CONNECTION_TIMEOUT = 522
int STATUS_CONTINUE = 100
int STATUS_CREATED = 201
int STATUS_EARLY_HINTS = 103
int STATUS_EXPECTATION_FAILED = 417
int STATUS_FAILED_DEPENDENCY = 424
int STATUS_FORBIDDEN = 403
int STATUS_FOUND = 302
int STATUS_GATEWAY_TIMEOUT = 504
int STATUS_GONE = 410
int STATUS_HTTP_REQUEST_SENT_TO_HTTPS_PORT = 497
int STATUS_IM_A_TEAPOT = 418
int STATUS_IM_USED = 226
int STATUS_INSUFFICIENT_STORAGE = 507
int STATUS_INTERNAL_SERVER_ERROR = 500
int STATUS_INVALID_SSL_CERTIFICATE = 526
int STATUS_INVALID_TOKEN_ESRI = 498
int STATUS_LENGTH_REQUIRED = 411
int STATUS_LOCKED = 423
int STATUS_LOGIN_TIMEOUT = 440
int STATUS_LOOP_DETECTED = 508
int STATUS_METHOD_FAILURE = 420
int STATUS_METHOD_NOT_ALLOWED = 405
int STATUS_MISDIRECTED_REQUEST = 421
int STATUS_MOVED_PERMANENTLY = 301
int STATUS_MULTIPLE_CHOICES = 300
int STATUS_MULTI_STATUS = 207
int STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511
int STATUS_NETWORK_CONNECT_TIMEOUT_ERROR = 599
int STATUS_NETWORK_READ_TIMEOUT_ERROR = 598
int STATUS_NON_AUTHORITATIVE_INFORMATION = 203
int STATUS_NOT_ACCEPTABLE = 406
int STATUS_NOT_EXTENDED = 510
int STATUS_NOT_FOUND = 404
int STATUS_NOT_IMPLEMENTED = 501
int STATUS_NOT_MODIFIED = 304
int STATUS_NO_CONTENT = 204
int STATUS_NO_RESPONSE = 444
int STATUS_OK = 200
int STATUS_ORIGIN_DNS_ERROR = 530
int STATUS_ORIGIN_IS_UNREACHABLE = 523
int STATUS_PAGE_EXPIRED = 419
int STATUS_PARTIAL_CONTENT = 206
int STATUS_PAYLOAD_TOO_LARGE = 413
int STATUS_PAYMENT_REQUIRED = 402
int STATUS_PERMANENT_REDIRECT = 308
int STATUS_PRECONDITION_FAILED = 412
int STATUS_PRECONDITION_REQUIRED = 428
int STATUS_PROCESSING = 102
int STATUS_PROXY_AUTHENTICATION_REQUIRED = 407
int STATUS_RAILGUN_ERROR = 527
int STATUS_RANGE_NOT_SATISFIABLE = 416
int STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431
int STATUS_REQUEST_HEADER_TOO_LARGE = 494
int STATUS_REQUEST_TIMEOUT = 408
int STATUS_RESERVED = 306
int STATUS_RESET_CONTENT = 205
int STATUS_RETRY_WITH = 449
int STATUS_SEE_OTHER = 303
int STATUS_SERVICE_UNAVAILABLE = 503
int STATUS_SSL_CERTIFICATE_ERROR = 495
int STATUS_SSL_CERTIFICATE_REQUIRED = 496
int STATUS_SSL_HANDSHAKE_FAILED = 525
int STATUS_SWITCHING_PROTOCOLS = 101
int STATUS_TEMPORARY_REDIRECT = 307
int STATUS_THIS_IS_FINE = 218
int STATUS_TIMEOUT_OCCURRED = 524
int STATUS_TOO_EARLY = 425
int STATUS_TOO_MANY_REQUESTS = 429
int STATUS_UNAUTHORIZED = 401
int STATUS_UNAVAILABLE_FOR_LEGAL_REASONS = 451
int STATUS_UNKNOWN_ERROR = 520
int STATUS_UNPROCESSABLE_ENTITY = 422
int STATUS_UNSUPPORTED_MEDIA_TYPE = 415
int STATUS_UPGRADE_REQUIRED = 426
int STATUS_URI_TOO_LONG = 414
int STATUS_USE_PROXY = 305
int STATUS_VARIANT_ALSO_NEGOTIATES = 506
int STATUS_VERSION_NOT_SUPPORTED = 505
int STATUS_WEB_SERVER_IS_DOWN = 521

Http\Message\Interfaces\ServerRequestFactoryInterface

Interface Source on GitHub

  • Phalcon\Http\Message\Interfaces\ServerRequestFactoryInterface

Method Summary

Methods

Public · 1

createServerRequest()

public function createServerRequest(
    string $method,
    mixed $uri,
    array $serverParams = []
): ServerRequestInterface;

Create a new server request.

Note that server-params are taken precisely as given - no parsing/processing of the given values is performed, and, in particular, no attempt is made to determine the HTTP method or URI, which must be provided explicitly.

Http\Message\Interfaces\ServerRequestInterface

Interface Source on GitHub

Representation of an incoming, server-side HTTP request.

Per the HTTP specification, this interface includes properties for each of the following:

  • Protocol version
  • HTTP method
  • URI
  • Headers
  • Message body

Additionally, it encapsulates all data as it has arrived to 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 MUST be 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.

Requests are considered immutable; all methods that might change state MUST be implemented such that they retain the internal state of the current message and return an instance that contains the changed state.

Uses Phalcon\Http\Message\Exception\InvalidArgumentException

Method Summary

Methods

Public · 13

getAttribute()

public function getAttribute(
    string $name,
    mixed $defaultValue = null
);

Retrieve a single derived request attribute.

Retrieves a single derived request attribute as described in getAttributes(). If the attribute has not been previously set, returns the default value as provided.

This method obviates the need for a hasAttribute() method, as it allows specifying a default value to return if the attribute is not found.

getAttributes()

public function getAttributes(): array;

Retrieve attributes derived from the request.

The 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.

getCookieParams()

public function getCookieParams(): array;

Retrieve cookies.

Retrieves cookies sent by the client to the server.

The data MUST be compatible with the structure of the $_COOKIE superglobal.

getParsedBody()

public function getParsedBody();

Retrieve 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 MUST 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 MUST be arrays or objects only. A null value indicates the absence of body content.

getQueryParams()

public function getQueryParams(): array;

Retrieve query string arguments.

Retrieves the deserialized query string arguments, if any.

Note: the query params might not be in sync with the URI or server params. 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 param.

getServerParams()

public function getServerParams(): array;

Retrieve server parameters.

Retrieves data related to the incoming request environment, typically derived from PHP's $_SERVER superglobal. The data IS NOT REQUIRED to originate from $_SERVER.

getUploadedFiles()

public function getUploadedFiles(): array;

Retrieve normalized file upload data.

This method returns upload metadata in a normalized tree, with each leaf an instance of Psr\Http\Message\UploadedFileInterface.

These values MAY be prepared from $_FILES or the message body during instantiation, or MAY be injected via withUploadedFiles().

withAttribute()

public function withAttribute(
    string $name,
    mixed $value
): ServerRequestInterface;

Return an instance with the specified derived request attribute.

This method allows setting a single derived request attribute as described in getAttributes().

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated attribute.

withCookieParams()

public function withCookieParams( array $cookies ): ServerRequestInterface;

Return an instance with the specified cookies.

The data IS NOT REQUIRED to come from the $_COOKIE superglobal, but MUST be compatible with the structure of $_COOKIE. Typically, this data will be injected at instantiation.

This method MUST NOT update the related Cookie header of the request instance, nor related values in the server params.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated cookie values.

withParsedBody()

public function withParsedBody( mixed $data ): ServerRequestInterface;

Return an instance with the specified body parameters.

These MAY be injected during instantiation.

If the request Content-Type is either application/x-www-form-urlencoded or multipart/form-data, and the request method is POST, use this method ONLY to inject the contents of $_POST.

The data IS NOT REQUIRED to come from $_POST, but MUST 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.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated body parameters.

withQueryParams()

public function withQueryParams( array $query ): ServerRequestInterface;

Return an instance with the specified query string arguments.

These values SHOULD remain immutable over the course of the incoming request. They MAY be injected during instantiation, such as from PHP's $_GET superglobal, or MAY be derived from some other value such as the URI. In cases where the arguments are parsed from the URI, the data MUST be compatible with what PHP's parse_str() would return for purposes of how duplicate query parameters are handled, and how nested sets are handled.

Setting query string arguments MUST NOT change the URI stored by the request, nor the values in the server params.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated query string arguments.

withUploadedFiles()

public function withUploadedFiles( array $uploadedFiles ): ServerRequestInterface;

Create a new instance with the specified uploaded files.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated body parameters.

withoutAttribute()

public function withoutAttribute( string $name ): ServerRequestInterface;

Return an instance that removes the specified derived request attribute.

This method allows removing a single derived request attribute as described in getAttributes().

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that removes the attribute.

Http\Message\Interfaces\StreamFactoryInterface

Interface Source on GitHub

  • Phalcon\Http\Message\Interfaces\StreamFactoryInterface

Uses Phalcon\Http\Message\Exception\InvalidArgumentException · Phalcon\Http\Message\Exception\RuntimeException

Method Summary

Methods

Public · 3

createStream()

public function createStream( string $content = "" ): StreamInterface;

Create a new stream from a string.

The stream SHOULD be created with a temporary resource.

createStreamFromFile()

public function createStreamFromFile(
    string $filename,
    string $mode = "r"
): StreamInterface;

Create a stream from an existing file.

The file MUST be opened using the given mode, which may be any mode supported by the fopen function.

The $filename MAY be any string supported by fopen().

createStreamFromResource()

public function createStreamFromResource( mixed $phpResource ): StreamInterface;

Create a new stream from an existing resource.

The stream MUST be readable and may be writable.

Http\Message\Interfaces\StreamInterface

Interface Source on GitHub

Describes a data stream.

Typically, an instance will wrap a PHP stream; this interface provides a wrapper around the most common operations, including serialization of the entire stream to a string.

  • Phalcon\Http\Message\Interfaces\StreamInterface

Uses Phalcon\Http\Message\Exception\RuntimeException

Method Summary

Methods

Public · 15

__toString()

public function __toString();

Reads all data from the stream into a string, from the beginning to end.

This method MUST attempt to seek to the beginning of the stream before reading data and read the stream until the end is reached.

Warning: This could attempt to load a large amount of data into memory.

This method MUST NOT raise an exception in order to conform with PHP's string casting operations.

@see https://php.net/manual/en/language.oop5.magic.php#object.tostring

close()

public function close();

Closes the stream and any underlying resources.

detach()

public function detach();

Separates any underlying resources from the stream.

After the stream has been detached, the stream is in an unusable state.

eof()

public function eof(): bool;

Returns true if the stream is at the end of the stream.

getContents()

public function getContents(): string;

Returns the remaining contents in a string

getMetadata()

public function getMetadata( string|null $key = null );

Get stream metadata as an associative array or retrieve a specific key.

The keys returned are identical to the keys returned from PHP's stream_get_meta_data() function.

@link https://php.net/manual/en/function.stream-get-meta-data.php

getSize()

public function getSize(): int|null;

Get the size of the stream if known.

isReadable()

public function isReadable(): bool;

Returns whether the stream is readable.

isSeekable()

public function isSeekable(): bool;

Returns whether the stream is seekable.

isWritable()

public function isWritable(): bool;

Returns whether the stream is writable.

read()

public function read( int $length ): string;

Read data from the stream.

rewind()

public function rewind(): void;

Seek to the beginning of the stream.

If the stream is not seekable, this method will raise an exception; otherwise, it will perform a seek(0).

seek()

public function seek(
    int $offset,
    int $whence = SEEK_SET
): void;

Seek to a position in the stream.

@link https://www.php.net/manual/en/function.fseek.php

tell()

public function tell(): int;

Returns the current position of the file read/write pointer

write()

public function write( string $data ): int;

Write data to the stream.

Http\Message\Interfaces\UploadedFileFactoryInterface

Interface Source on GitHub

  • Phalcon\Http\Message\Interfaces\UploadedFileFactoryInterface

Uses Phalcon\Http\Message\Exception\InvalidArgumentException

Method Summary

Methods

Public · 1

createUploadedFile()

public function createUploadedFile(
    StreamInterface $stream,
    int|null $size = null,
    int $error = UPLOAD_ERR_OK,
    string|null $clientFilename = null,
    string|null $clientMediaType = null
): UploadedFileInterface;

Create a new uploaded file.

If a size is not provided it will be determined by checking the size of the file.

@see https://php.net/manual/features.file-upload.post-method.php @see https://php.net/manual/features.file-upload.errors.php

Http\Message\Interfaces\UploadedFileInterface

Interface Source on GitHub

Value object representing a file uploaded through an HTTP request.

Instances of this interface are considered immutable; all methods that might change state MUST be implemented such that they retain the internal state of the current instance and return an instance that contains the changed state.

  • Phalcon\Http\Message\Interfaces\UploadedFileInterface

Uses Phalcon\Http\Message\Exception\InvalidArgumentException · Phalcon\Http\Message\Exception\RuntimeException

Method Summary

Methods

Public · 6

getClientFilename()

public function getClientFilename(): string|null;

Retrieve the filename sent by the client.

Do not trust the value returned by this method. A client could send a malicious filename with the intention to corrupt or hack your application.

Implementations SHOULD return the value stored in the "name" key of the file in the $_FILES array.

getClientMediaType()

public function getClientMediaType(): string|null;

Retrieve the media type sent by the client.

Do not trust the value returned by this method. A client could send a malicious media type with the intention to corrupt or hack your application.

Implementations SHOULD return the value stored in the "type" key of the file in the $_FILES array.

getError()

public function getError(): int;

Retrieve the error associated with the uploaded file.

The return value MUST be one of PHP's UPLOAD_ERR_XXX constants.

If the file was uploaded successfully, this method MUST return UPLOAD_ERR_OK.

Implementations SHOULD return the value stored in the "error" key of the file in the $_FILES array.

@see https://php.net/manual/en/features.file-upload.errors.php

getSize()

public function getSize(): int|null;

Retrieve the file size.

Implementations SHOULD return the value stored in the "size" key of the file in the $_FILES array if available, as PHP calculates this based on the actual size transmitted.

getStream()

public function getStream(): StreamInterface;

Retrieve a stream representing the uploaded file.

This method MUST return a StreamInterface instance, representing the uploaded file. The purpose of this method is to allow utilizing native PHP stream functionality to manipulate the file upload, such as stream_copy_to_stream() (though the result will need to be decorated in a native PHP stream wrapper to work with such functions).

If the moveTo() method has been called previously, this method MUST raise an exception.

moveTo()

public function moveTo( string $targetPath ): void;

Move the uploaded file to a new location.

Use this method as an alternative to move_uploaded_file(). This method is guaranteed to work in both SAPI and non-SAPI environments. Implementations must determine which environment they are in, and use the appropriate method (move_uploaded_file(), rename(), or a stream operation) to perform the operation.

$targetPath may be an absolute path, or a relative path. If it is a relative path, resolution should be the same as used by PHP's rename() function.

The original file or stream MUST be removed on completion.

If this method is called more than once, any subsequent calls MUST raise an exception.

When used in an SAPI environment where $_FILES is populated, when writing files via moveTo(), is_uploaded_file() and move_uploaded_file() SHOULD be used to ensure permissions and upload status are verified correctly.

If you wish to move to a stream, use getStream(), as SAPI operations cannot guarantee writing to stream destinations.

@see https://php.net/is_uploaded_file @see https://php.net/move_uploaded_file

Http\Message\Interfaces\UriFactoryInterface

Interface Source on GitHub

  • Phalcon\Http\Message\Interfaces\UriFactoryInterface

Uses Phalcon\Http\Message\Exception\InvalidArgumentException

Method Summary

Methods

Public · 1

createUri()

public function createUri( string $uri = "" ): UriInterface;

Create a new URI.

Http\Message\Interfaces\UriInterface

Interface Source on GitHub

Value object representing a URI.

This interface is meant to represent URIs according to RFC 3986 and to provide methods for most common operations. Additional functionality for working with URIs can be provided on top of the interface or externally. Its primary use is for HTTP requests, but may also be used in other contexts.

Instances of this interface are considered immutable; all methods that might change state MUST be implemented such that they retain the internal state of the current instance and return an instance that contains the changed state.

Typically, the Host header will be also be present in the request message. For server-side requests, the scheme will typically be discoverable in the server parameters.

@link https://tools.ietf.org/html/rfc3986 (the URI specification)

  • Phalcon\Http\Message\Interfaces\UriInterface

Uses Phalcon\Http\Message\Exception\InvalidArgumentException

Method Summary

Methods

Public · 16

__toString()

public function __toString(): string;

Return the string representation as a URI reference.

Depending on which components of the URI are present, the resulting string is either a full URI or relative reference according to RFC 3986, Section 4.1. The method concatenates the various components of the URI, using the appropriate delimiters:

  • If a scheme is present, it MUST be suffixed by ":".
  • If an authority is present, it MUST be prefixed by "//".
  • The path can be concatenated without delimiters. But there are two cases where the path has to be adjusted to make the URI reference valid as PHP does not allow to throw an exception in __toString():
    • If the path is rootless and an authority is present, the path MUST be prefixed by "/".
    • If the path is starting with more than one "/" and no authority is present, the starting slashes MUST be reduced to one.
  • If a query is present, it MUST be prefixed by "?".
  • If a fragment is present, it MUST be prefixed by "#".

@see https://tools.ietf.org/html/rfc3986#section-4.1

getAuthority()

public function getAuthority(): string;

Retrieve the authority component of the URI.

If no authority information is present, this method MUST return an empty string.

The authority syntax of the URI is:

[user-info@]host[:port]

If the port component is not set or is the standard port for the current scheme, it SHOULD NOT be included.

@see https://tools.ietf.org/html/rfc3986#section-3.2

getFragment()

public function getFragment(): string;

Retrieve the fragment component of the URI.

If no fragment is present, this method MUST return an empty string.

The leading "#" character is not part of the fragment and MUST NOT be added.

The value returned MUST be percent-encoded, but MUST NOT double-encode any characters. To determine what characters to encode, please refer to RFC 3986, Sections 2 and 3.5.

@see https://tools.ietf.org/html/rfc3986#section-2 @see https://tools.ietf.org/html/rfc3986#section-3.5

getHost()

public function getHost(): string;

Retrieve the host component of the URI.

If no host is present, this method MUST return an empty string.

The value returned MUST be normalized to lowercase, per RFC 3986 Section 3.2.2.

@see https://tools.ietf.org/html/rfc3986#section-3.2.2

getPath()

public function getPath(): string;

Retrieve the path component of the URI.

The path can either be empty or absolute (starting with a slash) or rootless (not starting with a slash). Implementations MUST support all three syntaxes.

Normally, the empty path "" and absolute path "/" are considered equal as defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically do this normalization because in contexts with a trimmed base path, e.g. the front controller, this difference becomes significant. It's the task of the user to handle both "" and "/".

The value returned MUST be percent-encoded, but MUST NOT double-encode any characters. To determine what characters to encode, please refer to RFC 3986, Sections 2 and 3.3.

As an example, if the value should include a slash ("/") not intended as delimiter between path segments, that value MUST be passed in encoded form (e.g., "%2F") to the instance.

@see https://tools.ietf.org/html/rfc3986#section-2 @see https://tools.ietf.org/html/rfc3986#section-3.3

getPort()

public function getPort(): int|null;

Retrieve the port component of the URI.

If a port is present, and it is non-standard for the current scheme, this method MUST return it as an integer. If the port is the standard port used with the current scheme, this method SHOULD return null.

If no port is present, and no scheme is present, this method MUST return a null value.

If no port is present, but a scheme is present, this method MAY return the standard port for that scheme, but SHOULD return null.

getQuery()

public function getQuery(): string;

Retrieve the query string of the URI.

If no query string is present, this method MUST return an empty string.

The leading "?" character is not part of the query and MUST NOT be added.

The value returned MUST be percent-encoded, but MUST NOT double-encode any characters. To determine what characters to encode, please refer to RFC 3986, Sections 2 and 3.4.

As an example, if a value in a key/value pair of the query string should include an ampersand ("&") not intended as a delimiter between values, that value MUST be passed in encoded form (e.g., "%26") to the instance.

@see https://tools.ietf.org/html/rfc3986#section-2 @see https://tools.ietf.org/html/rfc3986#section-3.4

getScheme()

public function getScheme(): string;

Retrieve the scheme component of the URI.

If no scheme is present, this method MUST return an empty string.

The value returned MUST be normalized to lowercase, per RFC 3986 Section 3.1.

The trailing ":" character is not part of the scheme and MUST NOT be added.

@see https://tools.ietf.org/html/rfc3986#section-3.1

getUserInfo()

public function getUserInfo(): string;

Retrieve the user information component of the URI.

If no user information is present, this method MUST return an empty string.

If a user is present in the URI, this will return that value; additionally, if the password is also present, it will be appended to the user value, with a colon (":") separating the values.

The trailing "@" character is not part of the user information and MUST NOT be added.

withFragment()

public function withFragment( string $fragment ): UriInterface;

Return an instance with the specified URI fragment.

This method MUST retain the state of the current instance, and return an instance that contains the specified URI fragment.

Users can provide both encoded and decoded fragment characters. Implementations ensure the correct encoding as outlined in getFragment().

An empty fragment value is equivalent to removing the fragment.

withHost()

public function withHost( string $host ): UriInterface;

Return an instance with the specified host.

This method MUST retain the state of the current instance, and return an instance that contains the specified host.

An empty host value is equivalent to removing the host.

withPath()

public function withPath( string $path ): UriInterface;

Return an instance with the specified path.

This method MUST retain the state of the current instance, and return an instance that contains the specified path.

The path can either be empty or absolute (starting with a slash) or rootless (not starting with a slash). Implementations MUST support all three syntaxes.

If the path is intended to be domain-relative rather than path relative then it must begin with a slash ("/"). Paths not starting with a slash ("/") are assumed to be relative to some base path known to the application or consumer.

Users can provide both encoded and decoded path characters. Implementations ensure the correct encoding as outlined in getPath().

withPort()

public function withPort( int|null $port ): UriInterface;

Return an instance with the specified port.

This method MUST retain the state of the current instance, and return an instance that contains the specified port.

Implementations MUST raise an exception for ports outside the established TCP and UDP port ranges.

A null value provided for the port is equivalent to removing the port information.

withQuery()

public function withQuery( string $query ): UriInterface;

Return an instance with the specified query string.

This method MUST retain the state of the current instance, and return an instance that contains the specified query string.

Users can provide both encoded and decoded query characters. Implementations ensure the correct encoding as outlined in getQuery().

An empty query string value is equivalent to removing the query string.

withScheme()

public function withScheme( string $scheme ): UriInterface;

Return an instance with the specified scheme.

This method MUST retain the state of the current instance, and return an instance that contains the specified scheme.

Implementations MUST support the schemes "http" and "https" case insensitively, and MAY accommodate other schemes if required.

An empty scheme is equivalent to removing the scheme.

withUserInfo()

public function withUserInfo(
    string $user,
    string|null $password = null
): UriInterface;

Return an instance with the specified user information.

This method MUST retain the state of the current instance, and return an instance that contains the specified user information.

Password is optional, but the user information MUST include the user; an empty string for the user is equivalent to removing user information.

Http\Message\Request

Class Source on GitHub

Request object

Uses Phalcon\Http\Message\Interfaces\RequestInterface · Phalcon\Http\Message\Interfaces\RequestMethodInterface · Phalcon\Http\Message\Interfaces\StreamInterface · Phalcon\Http\Message\Interfaces\UriInterface · Phalcon\Http\Message\Stream\Input · Phalcon\Support\Collection\CollectionInterface

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $method = self::METHOD_GET,
    mixed $uri = null,
    mixed $body = "php://memory",
    mixed $headers = []
);

Request constructor.

Http\Message\Response

Class Source on GitHub

Response object

Uses Phalcon\Http\Message\Exception\InvalidArgumentException · Phalcon\Http\Message\Interfaces\ResponseInterface · Phalcon\Http\Message\Interfaces\StreamInterface · Phalcon\Http\Traits\StatusPhrasesTrait

Method Summary

Properties

protected string $reasonPhrase = "" Gets the response reason phrase associated with the status code. Because a reason phrase is not a required element in a response status line, the reason phrase value MAY be empty. Implementations MAY choose to return the default RFC 7231 recommended reason phrase (or those listed in the IANA HTTP Status Code Registry) for the response's status code. @see https://tools.ietf.org/html/rfc7231#section-6 @see https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
protected int $statusCode = 200 Gets the response status code. The status code is a 3-digit integer result code of the server's attempt to understand and satisfy the request.

Methods

Public · 4

__construct()

public function __construct(
    mixed $body = "php://memory",
    int $code = 200,
    array $headers = []
);

Response constructor.

getReasonPhrase()

public function getReasonPhrase(): string;

getStatusCode()

public function getStatusCode(): int;

withStatus()

public function withStatus(
    int $code,
    string $reasonPhrase = ""
): ResponseInterface;

Return an instance with the specified status code and, optionally, reason phrase.

If no reason phrase is specified, implementations MAY choose to default to the RFC 7231 or IANA recommended reason phrase for the response's status code.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated status and reason phrase.

@see https://tools.ietf.org/html/rfc7231#section-6 @see https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

Protected · 1

processCode()

protected function processCode(
    int $code,
    string $phrase = ""
): void;

Set a valid status code and phrase

Http\Message\ResponseStatusCodeInterface

Interface Source on GitHub

Backward-compatible interface so that Phalcon\Http\Message\ResponseStatusCodeInterface resolves to the same set of constants as the canonical Phalcon\Http\Message\Interfaces\ResponseStatusCodeInterface.

Uses Phalcon\Http\Message\Interfaces\ResponseStatusCodeInterface

Http\Message\ServerRequest

Class Source on GitHub

ServerRequest

Uses Phalcon\Http\Message\Exception\InvalidArgumentException · Phalcon\Http\Message\Interfaces\ServerRequestInterface · Phalcon\Http\Message\Interfaces\StreamInterface · Phalcon\Http\Message\Interfaces\UploadedFileInterface · Phalcon\Http\Message\Interfaces\UriInterface · Phalcon\Http\Message\Stream\Input · Phalcon\Support\Collection · Phalcon\Support\Collection\CollectionInterface

Method Summary

Properties

protected CollectionInterface $attributes
protected array $cookieParams = [] Retrieve cookies. Retrieves cookies sent by the client to the server. The data MUST be compatible with the structure of the $_COOKIE superglobal.
protected mixed $parsedBody = null Retrieve 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 MUST 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 MUST be arrays or objects only. A null value indicates the absence of body content.
protected array $queryParams = [] Retrieve query string arguments. Retrieves the deserialized query string arguments, if any. Note: the query params might not be in sync with the URI or server params. 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 param.
protected array $serverParams = [] Retrieve server parameters. Retrieves data related to the incoming request environment, typically derived from PHP's $_SERVER superglobal. The data IS NOT REQUIRED to originate from $_SERVER.
protected array $uploadedFiles = [] Retrieve normalized file upload data. This method returns upload metadata in a normalized tree, with each leaf an instance of Phalcon\Http\Message\UploadedFileInterface. These values MAY be prepared from $_FILES or the message body during instantiation, or MAY be injected via withUploadedFiles().

Methods

Public · 14

__construct()

public function __construct(
    string $method = self::METHOD_GET,
    mixed $uri = null,
    array $serverParams = [],
    mixed $body = "php://input",
    mixed $headers = [],
    array $cookies = [],
    array $queryParams = [],
    array $uploadFiles = [],
    mixed $parsedBody = null,
    string $protocol = "1.1"
);

ServerRequest constructor.

getAttribute()

public function getAttribute(
    string $name,
    mixed $defaultValue = null
);

Retrieve a single derived request attribute.

Retrieves a single derived request attribute as described in getAttributes(). If the attribute has not been previously set, returns the default value as provided.

This method obviates the need for a hasAttribute() method, as it allows specifying a default value to return if the attribute is not found.

getAttributes()

public function getAttributes(): array;

Retrieve attributes derived from the request.

The 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.

getCookieParams()

public function getCookieParams(): array;

getParsedBody()

public function getParsedBody();

getQueryParams()

public function getQueryParams(): array;

getServerParams()

public function getServerParams(): array;

getUploadedFiles()

public function getUploadedFiles(): array;

withAttribute()

public function withAttribute(
    string $name,
    mixed $value
): ServerRequest;

Return an instance with the specified derived request attribute.

This method allows setting a single derived request attribute as described in getAttributes().

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated attribute.

withCookieParams()

public function withCookieParams( array $cookies ): ServerRequest;

Return an instance with the specified cookies.

The data IS NOT REQUIRED to come from the $_COOKIE superglobal, but MUST be compatible with the structure of $_COOKIE. Typically, this data will be injected at instantiation.

This method MUST NOT update the related Cookie header of the request instance, nor related values in the server params.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated cookie values.

withParsedBody()

public function withParsedBody( mixed $data ): ServerRequest;

Return an instance with the specified body parameters.

These MAY be injected during instantiation.

If the request Content-Type is either application/x-www-form-urlencoded or multipart/form-data, and the request method is POST, use this method ONLY to inject the contents of $_POST.

The data IS NOT REQUIRED to come from $_POST, but MUST 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.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated body parameters.

withQueryParams()

public function withQueryParams( array $query ): ServerRequest;

Return an instance with the specified query string arguments.

These values SHOULD remain immutable over the course of the incoming request. They MAY be injected during instantiation, such as from PHP's $_GET superglobal, or MAY be derived from some other value such as the URI. In cases where the arguments are parsed from the URI, the data MUST be compatible with what PHP's parse_str() would return for purposes of how duplicate query parameters are handled, and how nested sets are handled.

Setting query string arguments MUST NOT change the URI stored by the request, nor the values in the server params.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated query string arguments.

withUploadedFiles()

public function withUploadedFiles( array $uploadedFiles ): ServerRequest;

Create a new instance with the specified uploaded files.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated body parameters.

withoutAttribute()

public function withoutAttribute( string $name ): ServerRequest;

Return an instance that removes the specified derived request attribute.

This method allows removing a single derived request attribute as described in getAttributes().

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that removes the attribute.

Http\Message\Stream

Class Source on GitHub

Stream/file OO class

@property resource|null $handle @property resource|string $stream

Uses Exception · Phalcon\Http\Message\Exception\RuntimeException · Phalcon\Http\Message\Interfaces\StreamInterface · Phalcon\Traits\Php\FileTrait

Method Summary

Properties

protected resource|null $handle = null
protected resource|string $stream

Methods

Public · 18

__construct()

public function __construct(
    mixed $stream,
    string $mode = "rb"
);

Stream constructor.

__destruct()

public function __destruct();

Closes the stream when the destructed.

__toString()

public function __toString(): string;

Reads all data from the stream into a string, from the beginning to end.

This method MUST attempt to seek to the beginning of the stream before reading data and read the stream until the end is reached.

Warning: This could attempt to load a large amount of data into memory.

This method MUST NOT raise an exception in order to conform with PHP's string casting operations.

@see https://php.net/manual/en/language.oop5.magic.php#object.tostring

close()

public function close(): void;

Closes the stream and any underlying resources.

detach()

public function detach();

Separates any underlying resources from the stream.

After the stream has been detached, the stream is in an unusable state.

eof()

public function eof(): bool;

Returns true if the end of the stream has been reached

getContents()

public function getContents(): string;

Returns the remaining contents in a string

getMetadata()

public function getMetadata( string|null $key = null );

Get stream metadata as an associative array or retrieve a specific key.

The keys returned are identical to the keys returned from PHP's stream_get_meta_data() function.

getSize()

public function getSize(): int|null;

Get the size of the stream if known.

isReadable()

public function isReadable(): bool;

Returns whether the stream is readable.

isSeekable()

public function isSeekable(): bool;

Returns whether the stream is seekable.

isWritable()

public function isWritable(): bool;

Returns whether the stream is writable.

read()

public function read( int $length ): string;

Read data from the stream.

rewind()

public function rewind(): void;

Seek to the beginning of the stream.

If the stream is not seekable, this method will raise an exception; otherwise, it will perform a seek(0).

seek()

public function seek(
    int $offset,
    int $whence = 0
): void;

Seek to a position in the stream.

setStream()

public function setStream(
    mixed $stream,
    string $mode = "rb"
): void;

Sets the stream - existing instance

tell()

public function tell(): int;

Returns the current position of the file read/write pointer

write()

public function write( string $data ): int;

Write data to the stream.

Http\Message\Stream\Input

Class Source on GitHub

Describes a data stream from "php://input"

Typically, an instance will wrap a PHP stream; this interface provides a wrapper around the most common operations, including serialization of the entire stream to a string.

@property string $data @property bool $eof

Uses Phalcon\Http\Message\Exception\RuntimeException · Phalcon\Http\Message\Stream

Method Summary

Methods

Public · 5

__construct()

public function __construct();

Input constructor.

__toString()

public function __toString(): string;

Reads all data from the stream into a string, from the beginning to end.

This method MUST attempt to seek to the beginning of the stream before reading data and read the stream until the end is reached.

Warning: This could attempt to load a large amount of data into memory.

This method MUST NOT raise an exception in order to conform with PHP's string casting operations.

@see https://php.net/manual/en/language.oop5.magic.php#object.tostring

getContents()

public function getContents( int $length = -1 ): string;

Returns the remaining contents in a string

isWritable()

public function isWritable(): bool;

Returns whether the stream is writeable.

read()

public function read( int $length ): string;

Read data from the stream.

Http\Message\Stream\Memory

Class Source on GitHub

Describes a data stream from "php://memory"

Typically, an instance will wrap a PHP stream; this interface provides a wrapper around the most common operations, including serialization of the entire stream to a string.

Uses Phalcon\Http\Message\Stream

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $mode = "rb" );

Constructor

Http\Message\Stream\Temp

Class Source on GitHub

Describes a data stream from "php://temp"

Typically, an instance will wrap a PHP stream; this interface provides a wrapper around the most common operations, including serialization of the entire stream to a string.

Uses Phalcon\Http\Message\Stream

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $mode = "rb" );

Constructor

Http\Message\Traits\MessageTrait

Trait Source on GitHub

Message methods

  • Phalcon\Http\Message\Traits\MessageTrait

Uses Phalcon\Http\Message\Exception\InvalidArgumentException · Phalcon\Http\Message\Headers · Phalcon\Http\Message\Stream · Psr\Http\Message\MessageInterface · Psr\Http\Message\StreamInterface

Method Summary

Properties

protected StreamInterface $body Gets the body of the message.
protected Headers $headers
protected string $protocolVersion = "1.1" Retrieves the HTTP protocol version as a string. The string MUST contain only the HTTP version number (e.g., '1.1', '1.0').

Methods

Public · 11

getBody()

public function getBody(): StreamInterface;

Return the body of the stream

getHeader()

public function getHeader( string $name ): array;

Retrieves a message header value by the given case-insensitive name.

This method returns an array of all the header values of the given case-insensitive header name.

If the header does not appear in the message, this method MUST return an empty array.

getHeaderLine()

public function getHeaderLine( string $name ): string;

Retrieves a comma-separated string of the values for a single header.

This method returns all the header values of the given case-insensitive header name as a string concatenated together using a comma.

NOTE: Not all header values may be appropriately represented using comma concatenation. For such headers, use getHeader() instead and supply your own delimiter when concatenating.

If the header does not appear in the message, this method MUST return an empty string.

getHeaders()

public function getHeaders(): array;

Retrieves all 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.

// Represent the headers as a string
foreach ($message->getHeaders() as $name => $values) {
    echo $name . ': ' . implode(', ', $values);
}

// Emit headers iteratively:
foreach ($message->getHeaders() as $name => $values) {
    foreach ($values as $value) {
        header(sprintf('%s: %s', $name, $value), false);
    }
}

While header names are not case-sensitive, getHeaders() will preserve the exact case in which headers were originally specified.

getProtocolVersion()

public function getProtocolVersion(): string;

Returns the protocol version

hasHeader()

public function hasHeader( string $name ): bool;

Checks if a header exists by the given case-insensitive name.

withAddedHeader()

public function withAddedHeader(
    string $name,
    mixed $value
): MessageInterface;

Return an instance with the specified 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.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new header and/or value.

withBody()

public function withBody( StreamInterface $body ): MessageInterface;

Return an instance with the specified message body.

The body MUST be a StreamInterface object.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return a new instance that has the new body stream.

withHeader()

public function withHeader(
    string $name,
    mixed $value
): MessageInterface;

Return 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().

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new and/or updated header and value.

withProtocolVersion()

public function withProtocolVersion( string $version ): MessageInterface;

Return an instance with the specified HTTP protocol version.

The version string MUST contain only the HTTP version number (e.g., '1.1', '1.0').

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new protocol version.

withoutHeader()

public function withoutHeader( string $name ): MessageInterface;

Return an instance without the specified header.

Header resolution MUST be done without case-sensitivity.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that removes the named header.

Protected · 2

processBody()

final protected function processBody(
    mixed $body = "php://memory",
    string $mode = "r+b"
): StreamInterface;

Set a valid stream

processProtocol()

final protected function processProtocol( string $protocol = "" ): string;

Checks the protocol

Http\Message\Traits\RequestTrait

Trait Source on GitHub

Request methods

@property Headers $headers

  • Phalcon\Http\Message\Traits\RequestTrait

Uses Phalcon\Http\Message\Exception\InvalidArgumentException · Phalcon\Http\Message\Headers · Phalcon\Http\Message\Interfaces\RequestMethodInterface · Phalcon\Http\Message\Uri · Psr\Http\Message\RequestInterface · Psr\Http\Message\UriInterface

Method Summary

Properties

protected string $method = RequestMethodInterface::METHOD_GET Retrieves the HTTP method of the request.
protected string|null $requestTarget = null The request-target, if it has been provided or calculated.
protected UriInterface $uri Retrieves the URI instance. This method MUST return a UriInterface instance. @see https://tools.ietf.org/html/rfc3986#section-4.3

Methods

Public · 6

getMethod()

public function getMethod(): string;

getRequestTarget()

public function getRequestTarget(): string;

Retrieves the message's request target.

Retrieves 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() below).

getUri()

public function getUri(): UriInterface;

Returns the Uri object

withMethod()

public function withMethod( string $method ): RequestInterface;

Return an instance with the provided HTTP method.

While HTTP method names are typically all uppercase characters, HTTP method names are case-sensitive and thus implementations SHOULD NOT modify the given string.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the changed request method.

withRequestTarget()

public function withRequestTarget( string|null $requestTarget ): RequestInterface;

Return an instance with the specific request-target.

If the request needs a non-origin-form request-target - e.g., for specifying an absolute-form, authority-form, or asterisk-form - this method may be used to create an instance with the specified request-target, verbatim.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the changed request target.

@see https://tools.ietf.org/html/rfc7230#section-5.3 (for the various request-target forms allowed in request messages)

withUri()

public function withUri(
    UriInterface $uri,
    bool $preserveHost = false
): RequestInterface;

Returns an instance with the provided URI.

This method MUST update 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 MUST 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 MUST 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 MUST NOT update the Host header in the returned request.
  • If a Host header is present and non-empty, this method MUST NOT update the Host header in the returned request.

This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new UriInterface instance.

@see https://tools.ietf.org/html/rfc3986#section-4.3

Protected · 2

processMethod()

final protected function processMethod( string $method = "" ): string;

Check the method

processUri()

final protected function processUri( mixed $uri ): UriInterface;

Sets a valid Uri

Http\Message\UploadedFile

Class Source on GitHub

UploadedFile class

Uses Phalcon\Http\Message\Exception\InvalidArgumentException · Phalcon\Http\Message\Exception\RuntimeException · Phalcon\Http\Message\Interfaces\StreamInterface · Phalcon\Http\Message\Interfaces\UploadedFileInterface · Phalcon\Traits\Php\FileTrait

Method Summary

Methods

Public · 7

__construct()

public function __construct(
    mixed $stream,
    int|null $size = null,
    int $error = 0,
    string|null $clientFilename = null,
    string|null $clientMediaType = null
);

UploadedFile constructor.

getClientFilename()

public function getClientFilename(): string|null;

getClientMediaType()

public function getClientMediaType(): string|null;

getError()

public function getError(): int;

getSize()

public function getSize(): int|null;

getStream()

public function getStream(): StreamInterface;

Retrieve a stream representing the uploaded file.

This method MUST return a StreamInterface instance, representing the uploaded file. The purpose of this method is to allow utilizing native PHP stream functionality to manipulate the file upload, such as stream_copy_to_stream() (though the result will need to be decorated in a native PHP stream wrapper to work with such functions).

If the moveTo() method has been called previously, this method MUST raise an exception.

moveTo()

public function moveTo( string $targetPath ): void;

Move the uploaded file to a new location.

Use this method as an alternative to move_uploaded_file(). This method is guaranteed to work in both SAPI and non-SAPI environments. Implementations must determine which environment they are in, and use the appropriate method (move_uploaded_file(), rename(), or a stream operation) to perform the operation.

$targetPath may be an absolute path, or a relative path. If it is a relative path, resolution should be the same as used by PHP's rename() function.

The original file or stream MUST be removed on completion.

If this method is called more than once, any subsequent calls MUST raise an exception.

When used in an SAPI environment where $_FILES is populated, when writing files via moveTo(), is_uploaded_file() and move_uploaded_file() SHOULD be used to ensure permissions and upload status are verified correctly.

If you wish to move to a stream, use getStream(), as SAPI operations cannot guarantee writing to stream destinations.

@see https://php.net/is_uploaded_file @see https://php.net/move_uploaded_file

Http\Message\Uri

Class Source on GitHub

Uri

@property string $fragment @property string $host @property string $pass @property int|null $port @property string $query @property string $scheme @property string $userInfo

Uses Phalcon\Http\Message\Exception\InvalidArgumentException · Phalcon\Http\Message\Interfaces\UriInterface · Phalcon\Traits\Support\Helper\Str\StartsWithTrait

Method Summary

Constants

string CHAR_SUB_DELIMS = "!$&\\'\\(\\)\\*\\+,;=" Sub-delimiters used in user info, query strings and fragments. @const string
string CHAR_UNRESERVED = "a-zA-Z0-9_\\-\\.~\\pL" Unreserved characters used in user info, paths, query strings, and fragments. @const string

Properties

protected string $fragment = "" Returns the fragment of the URL
protected string $host = "" Retrieve the host component of the URI. If no host is present, this method MUST return an empty string. The value returned MUST be normalized to lowercase, per RFC 3986 Section 3.2.2. @see https://tools.ietf.org/html/rfc3986#section-3.2.2
protected string $path = "" Returns the path of the URL
protected int|null $port = null Retrieve the port component of the URI. If a port is present, and it is non-standard for the current scheme, this method MUST return it as an integer. If the port is the standard port used with the current scheme, this method SHOULD return null. If no port is present, and no scheme is present, this method MUST return a null value. If no port is present, but a scheme is present, this method MAY return the standard port for that scheme, but SHOULD return null.
protected string $query = "" Returns the query of the URL
protected string $scheme = "" Retrieve the scheme component of the URI. If no scheme is present, this method MUST return an empty string. The value returned MUST be normalized to lowercase, per RFC 3986 Section 3.1. The trailing ":" character is not part of the scheme and MUST NOT be added. @see https://tools.ietf.org/html/rfc3986#section-3.1
protected string $userInfo = ""

Methods

Public · 17

__construct()

public function __construct( string $uri = "" );

Uri constructor.

__toString()

public function __toString(): string;

Return the string representation as a URI reference.

Depending on which components of the URI are present, the resulting string is either a full URI or relative reference according to RFC 3986, Section 4.1. The method concatenates the various components of the URI, using the appropriate delimiters

getAuthority()

public function getAuthority(): string;

Retrieve the authority component of the URI.

getFragment()

public function getFragment(): string;

Returns the fragment of the URL

getHost()

public function getHost(): string;

Retrieve the host component of the URI.

If no host is present, this method MUST return an empty string.

The value returned MUST be normalized to lowercase, per RFC 3986 Section 3.2.2.

@see https://tools.ietf.org/html/rfc3986#section-3.2.2

getPath()

public function getPath(): string;

Returns the path of the URL

getPort()

public function getPort(): int|null;

Retrieve the port component of the URI.

If a port is present, and it is non-standard for the current scheme, this method MUST return it as an integer. If the port is the standard port used with the current scheme, this method SHOULD return null.

If no port is present, and no scheme is present, this method MUST return a null value.

If no port is present, but a scheme is present, this method MAY return the standard port for that scheme, but SHOULD return null.

getQuery()

public function getQuery(): string;

Returns the query of the URL

getScheme()

public function getScheme(): string;

Retrieve the scheme component of the URI.

If no scheme is present, this method MUST return an empty string.

The value returned MUST be normalized to lowercase, per RFC 3986 Section 3.1.

The trailing ":" character is not part of the scheme and MUST NOT be added.

@see https://tools.ietf.org/html/rfc3986#section-3.1

getUserInfo()

public function getUserInfo(): string;

Retrieve the user information component of the URI.

If no user information is present, this method MUST return an empty string.

If a user is present in the URI, this will return that value; additionally, if the password is also present, it will be appended to the user value, with a colon (":") separating the values.

The trailing "@" character is not part of the user information and MUST NOT be added.

withFragment()

public function withFragment( string $fragment ): UriInterface;

Return an instance with the specified URI fragment.

This method MUST retain the state of the current instance, and return an instance that contains the specified URI fragment.

Users can provide both encoded and decoded fragment characters. Implementations ensure the correct encoding as outlined in getFragment().

An empty fragment value is equivalent to removing the fragment.

withHost()

public function withHost( string $host ): UriInterface;

Return an instance with the specified host.

This method MUST retain the state of the current instance, and return an instance that contains the specified host.

An empty host value is equivalent to removing the host.

withPath()

public function withPath( string $path ): UriInterface;

Return an instance with the specified path.

This method MUST retain the state of the current instance, and return an instance that contains the specified path.

The path can either be empty or absolute (starting with a slash) or rootless (not starting with a slash). Implementations MUST support all three syntaxes.

If an HTTP path is intended to be host-relative rather than path-relative then it must begin with a slash ("/"). HTTP paths not starting with a slash are assumed to be relative to some base path known to the application or consumer.

Users can provide both encoded and decoded path characters. Implementations ensure the correct encoding as outlined in getPath().

withPort()

public function withPort( int|null $port ): UriInterface;

Return an instance with the specified port.

This method MUST retain the state of the current instance, and return an instance that contains the specified port.

Implementations MUST raise an exception for ports outside the established TCP and UDP port ranges.

A null value provided for the port is equivalent to removing the port information.

withQuery()

public function withQuery( string $query ): UriInterface;

Return an instance with the specified query string.

This method MUST retain the state of the current instance, and return an instance that contains the specified query string.

Users can provide both encoded and decoded query characters. Implementations ensure the correct encoding as outlined in getQuery().

An empty query string value is equivalent to removing the query string.

withScheme()

public function withScheme( string $scheme ): UriInterface;

Return an instance with the specified scheme.

This method MUST retain the state of the current instance, and return an instance that contains the specified scheme.

Implementations MUST support the schemes "http" and "https" case insensitively, and MAY accommodate other schemes if required.

An empty scheme is equivalent to removing the scheme.

withUserInfo()

public function withUserInfo(
    string $user,
    string|null $password = null
): UriInterface;

Return an instance with the specified user information.

Protected · 1

phpParseUrl()

protected function phpParseUrl( string $url );

Proxy method for parse_url for tests

Http\Request

Class Source on GitHub

Encapsulates request information for easy and secure access from application controllers.

The request object is a simple value object that is passed between the dispatcher and controller classes. It packages the HTTP request environment.

use Phalcon\Http\Request;

$request = new Request();

if ($request->isPost() && $request->isAjax()) {
    echo "Request was made using POST and AJAX";
}

// Retrieve SERVER variables
$request->getServer("HTTP_HOST");

// GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT
$request->getMethod();

// An array of languages the client accepts
$request->getLanguages();

Uses Phalcon\Contracts\Http\AttributeRequest · Phalcon\Di\AbstractInjectionAware · Phalcon\Di\DiInterface · Phalcon\Events\EventsAwareInterface · Phalcon\Events\Exception · Phalcon\Events\Traits\EventsAwareTrait · Phalcon\Filter\FilterInterface · Phalcon\Http\Message\Interfaces\RequestMethodInterface · Phalcon\Http\Request\Bag\AttributeBag · Phalcon\Http\Request\Exception · Phalcon\Http\Request\Exceptions\FilterServiceUnavailable · Phalcon\Http\Request\Exceptions\InvalidHost · Phalcon\Http\Request\Exceptions\InvalidHttpMethod · Phalcon\Http\Request\Exceptions\MissingFilters · Phalcon\Http\Request\Exceptions\SanitizerNotFound · Phalcon\Http\Request\File · Phalcon\Http\Request\FileInterface · Phalcon\Support\Helper\Json\Decode · Phalcon\Traits\Php\FileTrait · stdClass

Method Summary

public mixed get(string|null $name = null,mixed $filters = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false) Gets a variable from the $_REQUEST superglobal applying filters if public array getAcceptableContent() Gets an array with mime/types and their quality accepted by the public AttributeBag getAttributes() Returns the request attributes bag. Attributes are arbitrary, public array|null getBasicAuth() Gets auth info accepted by the browser/client from public string getBestAccept() Gets best mime/type accepted by the browser/client from public string getBestCharset() Gets best charset accepted by the browser/client from public string getBestLanguage() Gets the best language accepted by the browser/client from public bool|string getClientAddress( bool $trustForwardedHeader = false ) Gets most possible client IP Address. This method searches in public array getClientCharsets() Gets a charsets array and their quality accepted by the browser/client public string|null getContentType() Gets content type which request has been made public array getDigestAuth() Gets auth info accepted by the browser/client from public mixed getFilteredData(string $methodKey,string $method,string|null $name = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false) Gets filtered data public mixed getFilteredPatch(string|null $name = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false) Retrieves a patch value always sanitized with the preset filters public mixed getFilteredPost(string|null $name = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false) Retrieves a post value always sanitized with the preset filters public mixed getFilteredPut(string|null $name = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false) Retrieves a put value always sanitized with the preset filters public mixed getFilteredQuery(string|null $name = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false) Retrieves a query/get value always sanitized with the preset filters public string getHTTPReferer() Gets web page that refers active request. ie: https://www.google.com public string getHeader( string $header ) Gets HTTP header from request data public array getHeaders() Returns the available headers in the request public string getHttpHost() Gets host name used by the request. public bool getHttpMethodParameterOverride() Return the HTTP method parameter override flag public array|bool|stdClass getJsonRawBody( bool $associative = false ) Gets decoded JSON HTTP raw request body public array getLanguages() Gets languages array and their quality accepted by the browser/client public string getMethod() Gets HTTP method which request has been made public mixed getPatch(string|null $name = null,mixed $filters = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false) Gets a variable from put request public int getPort() Gets information about the port on which the request is made. public mixed getPost(string|null $name = null,mixed $filters = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false) Gets a variable from the $_POST superglobal applying filters if needed public string getPreferredIsoLocaleVariant() Gets the preferred ISO locale variant. public mixed getPut(string|null $name = null,mixed $filters = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false) Gets a variable from put request public mixed getQuery(string|null $name = null,mixed $filters = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false) Gets variable from $_GET superglobal applying filters if needed. public string getRawBody() Gets HTTP raw request body public string getScheme() Gets HTTP schema (http/https) public string|null getServer( string $name ) Gets variable from $_SERVER superglobal public string getServerAddress() Gets active server address IP public string getServerName() Gets active server name public string getURI( bool $onlyPath = false ) Gets HTTP URI which request has been made to public array getUploadedFiles(bool $onlySuccessful = false,bool $namedKeys = false) Gets attached files as Phalcon\Http\Request\File instances public string getUserAgent() Gets HTTP user agent used to make the request public bool has( string $name ) Checks whether $_REQUEST superglobal has certain index public bool hasFiles() Returns if the request has files or not public bool hasHeader( string $header ) Checks whether headers has certain index public bool hasPatch( string $name ) Checks whether the PATCH data has certain index public bool hasPost( string $name ) Checks whether $_POST superglobal has certain index public bool hasPut( string $name ) Checks whether the PUT data has certain index public bool hasQuery( string $name ) Checks whether $_GET superglobal has certain index public bool hasServer( string $name ) Checks whether $_SERVER superglobal has certain index public bool isAjax() Checks whether request has been made using ajax public bool isConnect() Checks whether HTTP method is CONNECT. public bool isDelete() Checks whether HTTP method is DELETE. public bool isGet() Checks whether HTTP method is GET. public bool isHead() Checks whether HTTP method is HEAD. public bool isJson() Checks whether request content type contains json data public bool isMethod(mixed $methods,bool $strict = false) Check if HTTP method match any of the passed methods public bool isOptions() Checks whether HTTP method is OPTIONS. public bool isPatch() Checks whether HTTP method is PATCH. public bool isPost() Checks whether HTTP method is POST. public bool isPurge() Checks whether HTTP method is PURGE (Squid and Varnish support). public bool isPut() Checks whether HTTP method is PUT. public bool isSecure() Checks whether request has been made using any secure layer public bool isSoap() Checks whether request has been made using SOAP public bool isStrictHostCheck() Checks if the Request::getHttpHost method will be use strict validation public bool isTrace() Checks whether HTTP method is TRACE. public bool isValidHttpMethod( string $method ) Checks if a method is a valid HTTP method public int numFiles( bool $onlySuccessful = false ) Returns the number of files available public static setHttpMethodParameterOverride( bool $override ) Set the HTTP method parameter override flag public static setParameterFilters(string $name,array $filters = [],array $scope = []) Sets automatic sanitizers/filters for a particular field and for public static setStrictHostCheck( bool $flag = true ) Sets if the Request::getHttpHost method must be use strict validation public static setTrustedProxies( array $trustedProxies ) Set a trusted proxy list for X-Forwarded-For header public static setTrustedProxyHeader( string $trustedProxyHeader ) This header takes priority when parsing HTTP headers protected string getBestQuality(array $qualityParts,string $name) Process a request header and return the one with best quality protected mixed getHelper(array $source,string|null $name = null,mixed $filters = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false) Helper to get data from superglobals, applying filters if needed. protected array getQualityHeader(string $serverIndex,string $name) Process a request header and return an array of values with their protected int hasFileHelper(mixed $data,bool $onlySuccessful) Recursively counts file in an array of files protected bool isIpAddressInCIDR(string $ip,string $cidr) Check if an IP address exists in CIDR range protected array resolveAuthorizationHeaders() Resolve authorization headers. protected array smoothFiles(array $names,array $types,array $tmpNames,array $sizes,array $errors,string $prefix) Smooth out $_FILES as a one dimension array with all files uploaded

Properties

protected AttributeBag|null $attributes = null
protected FilterInterface|null $filterService = null
protected bool $methodOverride = false
protected array|null $postCache = null
protected array $queryFilters = []
protected string $rawBody = ""
protected bool $strictHostCheck = false
protected array $trustedProxies = []
protected string $trustedProxyHeader = ""

Methods

Public · 69

get()

public function get(
    string|null $name = null,
    mixed $filters = null,
    mixed $defaultValue = null,
    bool $notAllowEmpty = false,
    bool $noRecursive = false
): mixed;

Gets a variable from the $_REQUEST superglobal applying filters if needed. If no parameters are given the $_REQUEST superglobal is returned

// Returns value from $_REQUEST["user_email"] without sanitizing
$userEmail = $request->get("user_email");

// Returns value from $_REQUEST["user_email"] with sanitizing
$userEmail = $request->get("user_email", "email");

getAcceptableContent()

public function getAcceptableContent(): array;

Gets an array with mime/types and their quality accepted by the browser/client from _SERVER["HTTP_ACCEPT"]

getAttributes()

public function getAttributes(): AttributeBag;

Returns the request attributes bag. Attributes are arbitrary, application-defined values attached to the request during its lifecycle (router, dispatcher, security components etc.). The bag is created empty on first access and the same instance is returned on every subsequent call.

$request->getAttributes()->set("user", $user);

$user = $request->getAttributes()->get("user");

getBasicAuth()

public function getBasicAuth(): array|null;

Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_USER"]

getBestAccept()

public function getBestAccept(): string;

Gets best mime/type accepted by the browser/client from _SERVER["HTTP_ACCEPT"]

getBestCharset()

public function getBestCharset(): string;

Gets best charset accepted by the browser/client from _SERVER["HTTP_ACCEPT_CHARSET"]

getBestLanguage()

public function getBestLanguage(): string;

Gets the best language accepted by the browser/client from _SERVER["HTTP_ACCEPT_LANGUAGE"]

getClientAddress()

public function getClientAddress( bool $trustForwardedHeader = false ): bool|string;

Gets most possible client IP Address. This method searches in $_SERVER["REMOTE_ADDR"] and optionally in $_SERVER["HTTP_X_FORWARDED_FOR"] and returns the first non-private or non-reserved IP address

The user provided trusted header takes priority before checking X-Forwarded-For header.

Using trusted proxies list, user has to provide a trusted list of proxy IPs

$request
    ->setTrustedProxies($trustedProxies)
    ->getClientAddress(true);
Using user provided trusted header, header should only ever contain 1 IP address, eg. HTTP_CLIENT_IP
$request
    ->setTrustedProxyHeader('HTTP_CLIENT_IP')
    ->setTrustedProxies($trustedProxies)
    ->getClientAddress(true);

getClientCharsets()

public function getClientCharsets(): array;

Gets a charsets array and their quality accepted by the browser/client from _SERVER["HTTP_ACCEPT_CHARSET"]

getContentType()

public function getContentType(): string|null;

Gets content type which request has been made

getDigestAuth()

public function getDigestAuth(): array;

Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_DIGEST"]

getFilteredData()

public function getFilteredData(
    string $methodKey,
    string $method,
    string|null $name = null,
    mixed $defaultValue = null,
    bool $notAllowEmpty = false,
    bool $noRecursive = false
): mixed;

Gets filtered data

getFilteredPatch()

public function getFilteredPatch(
    string|null $name = null,
    mixed $defaultValue = null,
    bool $notAllowEmpty = false,
    bool $noRecursive = false
): mixed;

Retrieves a patch value always sanitized with the preset filters

getFilteredPost()

public function getFilteredPost(
    string|null $name = null,
    mixed $defaultValue = null,
    bool $notAllowEmpty = false,
    bool $noRecursive = false
): mixed;

Retrieves a post value always sanitized with the preset filters

getFilteredPut()

public function getFilteredPut(
    string|null $name = null,
    mixed $defaultValue = null,
    bool $notAllowEmpty = false,
    bool $noRecursive = false
): mixed;

Retrieves a put value always sanitized with the preset filters

getFilteredQuery()

public function getFilteredQuery(
    string|null $name = null,
    mixed $defaultValue = null,
    bool $notAllowEmpty = false,
    bool $noRecursive = false
): mixed;

Retrieves a query/get value always sanitized with the preset filters

getHTTPReferer()

public function getHTTPReferer(): string;

Gets web page that refers active request. ie: https://www.google.com

getHeader()

public function getHeader( string $header ): string;

Gets HTTP header from request data

getHeaders()

public function getHeaders(): array;

Returns the available headers in the request

$_SERVER = [ "PHP_AUTH_USER" => "phalcon", "PHP_AUTH_PW" => "secret", ];

$headers = $request->getHeaders();

echo $headers["Authorization"]; // Basic cGhhbGNvbjpzZWNyZXQ=

getHttpHost()

public function getHttpHost(): string;

Gets host name used by the request.

Request::getHttpHost trying to find host name in following order:

  • $_SERVER["HTTP_HOST"]
  • $_SERVER["SERVER_NAME"]
  • $_SERVER["SERVER_ADDR"]

Optionally Request::getHttpHost validates and clean host name. The Request::$strictHostCheck can be used to validate host name.

Note: validation and cleaning have a negative performance impact because they use regular expressions.

use Phalcon\Http\Request;

$request = new Request;

$_SERVER["HTTP_HOST"] = "example.com";
$request->getHttpHost(); // example.com

$_SERVER["HTTP_HOST"] = "example.com:8080";
$request->getHttpHost(); // example.com:8080

$request->setStrictHostCheck(true);
$_SERVER["HTTP_HOST"] = "ex=am~ple.com";
$request->getHttpHost(); // UnexpectedValueException

$_SERVER["HTTP_HOST"] = "ExAmPlE.com";
$request->getHttpHost(); // example.com

getHttpMethodParameterOverride()

public function getHttpMethodParameterOverride(): bool;

Return the HTTP method parameter override flag

getJsonRawBody()

public function getJsonRawBody( bool $associative = false ): array|bool|stdClass;

Gets decoded JSON HTTP raw request body

getLanguages()

public function getLanguages(): array;

Gets languages array and their quality accepted by the browser/client from _SERVER["HTTP_ACCEPT_LANGUAGE"]

getMethod()

public function getMethod(): string;

Gets HTTP method which request has been made

If the X-HTTP-Method-Override header is set, and if the method is a POST, then it is used to determine the "real" intended HTTP method.

The _method request parameter can also be used to determine the HTTP method, but only if setHttpMethodParameterOverride(true) has been called.

The method is always an uppercased string.

getPatch()

public function getPatch(
    string|null $name = null,
    mixed $filters = null,
    mixed $defaultValue = null,
    bool $notAllowEmpty = false,
    bool $noRecursive = false
): mixed;

Gets a variable from put request

// Returns value from $_PATCH["user_email"] without sanitizing
$userEmail = $request->getPatch("user_email");

// Returns value from $_PATCH["user_email"] with sanitizing
$userEmail = $request->getPatch("user_email", "email");

getPort()

public function getPort(): int;

Gets information about the port on which the request is made.

getPost()

public function getPost(
    string|null $name = null,
    mixed $filters = null,
    mixed $defaultValue = null,
    bool $notAllowEmpty = false,
    bool $noRecursive = false
): mixed;

Gets a variable from the $_POST superglobal applying filters if needed If no parameters are given the $_POST superglobal is returned

// Returns value from $_POST["user_email"] without sanitizing
$userEmail = $request->getPost("user_email");

// Returns value from $_POST["user_email"] with sanitizing
$userEmail = $request->getPost("user_email", "email");

getPreferredIsoLocaleVariant()

public function getPreferredIsoLocaleVariant(): string;

Gets the preferred ISO locale variant.

Gets the preferred locale accepted by the client from the "Accept-Language" request HTTP header and returns the base part of it i.e. en instead of en-US.

Note: This method relies on the $_SERVER["HTTP_ACCEPT_LANGUAGE"] header.

@link https://www.iso.org/standard/50707.html

getPut()

public function getPut(
    string|null $name = null,
    mixed $filters = null,
    mixed $defaultValue = null,
    bool $notAllowEmpty = false,
    bool $noRecursive = false
): mixed;

Gets a variable from put request

// Returns value from $_PUT["user_email"] without sanitizing
$userEmail = $request->getPut("user_email");

// Returns value from $_PUT["user_email"] with sanitizing
$userEmail = $request->getPut("user_email", "email");

getQuery()

public function getQuery(
    string|null $name = null,
    mixed $filters = null,
    mixed $defaultValue = null,
    bool $notAllowEmpty = false,
    bool $noRecursive = false
): mixed;

Gets variable from $_GET superglobal applying filters if needed. If no parameters are given the $_GET superglobal is returned

// Returns value from $_GET["id"] without sanitizing
$id = $request->getQuery("id");

// Returns value from $_GET["id"] with sanitizing
$id = $request->getQuery("id", "int");

// Returns value from $_GET["id"] with a default value
$id = $request->getQuery("id", null, 150);

getRawBody()

public function getRawBody(): string;

Gets HTTP raw request body

getScheme()

public function getScheme(): string;

Gets HTTP schema (http/https)

getServer()

public function getServer( string $name ): string|null;

Gets variable from $_SERVER superglobal

getServerAddress()

public function getServerAddress(): string;

Gets active server address IP

getServerName()

public function getServerName(): string;

Gets active server name

getURI()

public function getURI( bool $onlyPath = false ): string;

Gets HTTP URI which request has been made to

// Returns /some/path?with=queryParams
$uri = $request->getURI();

// Returns /some/path
$uri = $request->getURI(true);

getUploadedFiles()

public function getUploadedFiles(
    bool $onlySuccessful = false,
    bool $namedKeys = false
): array;

Gets attached files as Phalcon\Http\Request\File instances

getUserAgent()

public function getUserAgent(): string;

Gets HTTP user agent used to make the request

has()

public function has( string $name ): bool;

Checks whether $_REQUEST superglobal has certain index

hasFiles()

public function hasFiles(): bool;

Returns if the request has files or not

hasHeader()

final public function hasHeader( string $header ): bool;

Checks whether headers has certain index

hasPatch()

public function hasPatch( string $name ): bool;

Checks whether the PATCH data has certain index

hasPost()

public function hasPost( string $name ): bool;

Checks whether $_POST superglobal has certain index

hasPut()

public function hasPut( string $name ): bool;

Checks whether the PUT data has certain index

hasQuery()

public function hasQuery( string $name ): bool;

Checks whether $_GET superglobal has certain index

hasServer()

final public function hasServer( string $name ): bool;

Checks whether $_SERVER superglobal has certain index

isAjax()

public function isAjax(): bool;

Checks whether request has been made using ajax

isConnect()

public function isConnect(): bool;

Checks whether HTTP method is CONNECT. if _SERVER["REQUEST_METHOD"]==="CONNECT"

isDelete()

public function isDelete(): bool;

Checks whether HTTP method is DELETE. if _SERVER["REQUEST_METHOD"]==="DELETE"

isGet()

public function isGet(): bool;

Checks whether HTTP method is GET. if _SERVER["REQUEST_METHOD"]==="GET"

isHead()

public function isHead(): bool;

Checks whether HTTP method is HEAD. if _SERVER["REQUEST_METHOD"]==="HEAD"

isJson()

public function isJson(): bool;

Checks whether request content type contains json data

isMethod()

public function isMethod(
    mixed $methods,
    bool $strict = false
): bool;

Check if HTTP method match any of the passed methods When strict is true it checks if validated methods are real HTTP methods

isOptions()

public function isOptions(): bool;

Checks whether HTTP method is OPTIONS. if _SERVER["REQUEST_METHOD"]==="OPTIONS"

isPatch()

public function isPatch(): bool;

Checks whether HTTP method is PATCH. if _SERVER["REQUEST_METHOD"]==="PATCH"

isPost()

public function isPost(): bool;

Checks whether HTTP method is POST. if _SERVER["REQUEST_METHOD"]==="POST"

isPurge()

public function isPurge(): bool;

Checks whether HTTP method is PURGE (Squid and Varnish support). if _SERVER["REQUEST_METHOD"]==="PURGE"

isPut()

public function isPut(): bool;

Checks whether HTTP method is PUT. if _SERVER["REQUEST_METHOD"]==="PUT"

isSecure()

public function isSecure(): bool;

Checks whether request has been made using any secure layer

isSoap()

public function isSoap(): bool;

Checks whether request has been made using SOAP

isStrictHostCheck()

public function isStrictHostCheck(): bool;

Checks if the Request::getHttpHost method will be use strict validation of host name or not

isTrace()

public function isTrace(): bool;

Checks whether HTTP method is TRACE. if _SERVER["REQUEST_METHOD"]==="TRACE"

isValidHttpMethod()

public function isValidHttpMethod( string $method ): bool;

Checks if a method is a valid HTTP method

numFiles()

public function numFiles( bool $onlySuccessful = false ): int;

Returns the number of files available

setHttpMethodParameterOverride()

public function setHttpMethodParameterOverride( bool $override ): static;

Set the HTTP method parameter override flag

setParameterFilters()

public function setParameterFilters(
    string $name,
    array $filters = [],
    array $scope = []
): static;

Sets automatic sanitizers/filters for a particular field and for particular methods

setStrictHostCheck()

public function setStrictHostCheck( bool $flag = true ): static;

Sets if the Request::getHttpHost method must be use strict validation of host name or not

setTrustedProxies()

public function setTrustedProxies( array $trustedProxies ): static;

Set a trusted proxy list for X-Forwarded-For header

setTrustedProxyHeader()

public function setTrustedProxyHeader( string $trustedProxyHeader ): static;

This header takes priority when parsing HTTP headers The header return only 1 single IP address, prefixed with HTTP_ eg. HTTP_CLIENT_IP.

Protected · 7

getBestQuality()

protected function getBestQuality(
    array $qualityParts,
    string $name
): string;

Process a request header and return the one with best quality

getHelper()

protected function getHelper(
    array $source,
    string|null $name = null,
    mixed $filters = null,
    mixed $defaultValue = null,
    bool $notAllowEmpty = false,
    bool $noRecursive = false
): mixed;

Helper to get data from superglobals, applying filters if needed. If no parameters are given the superglobal is returned.

getQualityHeader()

protected function getQualityHeader(
    string $serverIndex,
    string $name
): array;

Process a request header and return an array of values with their qualities

hasFileHelper()

protected function hasFileHelper(
    mixed $data,
    bool $onlySuccessful
): int;

Recursively counts file in an array of files

isIpAddressInCIDR()

protected function isIpAddressInCIDR(
    string $ip,
    string $cidr
): bool;

Check if an IP address exists in CIDR range

resolveAuthorizationHeaders()

protected function resolveAuthorizationHeaders(): array;

Resolve authorization headers.

smoothFiles()

protected function smoothFiles(
    array $names,
    array $types,
    array $tmpNames,
    array $sizes,
    array $errors,
    string $prefix
): array;

Smooth out $_FILES as a one dimension array with all files uploaded

Http\RequestInterface

Interface Source on GitHub

Interface for Phalcon\Http\Request

Uses Phalcon\Http\Request\FileInterface · stdClass

Method Summary

public mixed get(string|null $name = null,mixed $filters = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false) Gets a variable from the $_REQUEST superglobal applying filters if public array getAcceptableContent() Return an array with mime/types and their quality accepted by the public array|null getBasicAuth() Gets auth info accepted by the browser/client from public string getBestAccept() Return the best mime/type accepted by the browser/client from public string getBestCharset() Return the best charset accepted by the browser/client from public string getBestLanguage() Return the best language accepted by the browser/client from public bool|string getClientAddress( bool $trustForwardedHeader = false ) Return the most possible client IPv4 Address. This method searches in public array getClientCharsets() Return a charset array and their quality accepted by the browser/client public string|null getContentType() Return the content type which request has been made public array getDigestAuth() Return the auth info accepted by the browser/client from public string getHTTPReferer() Return the web page that refers active request. ie: https://phalcon.io public string getHeader( string $header ) Return the HTTP header from request data public array getHeaders() Return the available headers in the request public string getHttpHost() Return the host name used by the request. public array|bool|stdClass getJsonRawBody( bool $associative = false ) Return the decoded JSON HTTP raw request body public array getLanguages() Return the languages array and their quality accepted by the public string getMethod() Return the HTTP method which request has been made public int getPort() Return the information about the port on which the request is made public mixed getPost(string|null $name = null,mixed $filters = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false) Return a variable from the $_POST superglobal applying filters if needed. public getPut(string|null $name = null,mixed $filters = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false) Return a variable from put request public getQuery(string|null $name = null,mixed $filters = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false) Return a variable from $_GET superglobal applying filters if needed. public string getRawBody() Return the HTTP raw request body public string getScheme() Return the HTTP schema (http/https) public string|null getServer( string $name ) Return a variable from $_SERVER superglobal public string getServerAddress() Return the active server address IP public string getServerName() Return the active server name public string getURI( bool $onlyPath = false ) Return the HTTP URI which request has been made to public array getUploadedFiles(bool $onlySuccessful = false,bool $namedKeys = false) Return the attached files as Phalcon\Http\Request\FileInterface public string getUserAgent() Return the HTTP user agent used to make the request public bool has( string $name ) Return whether the $_REQUEST superglobal has certain index public bool hasFiles() Return whether the request includes attached files public bool hasHeader( string $header ) Return whether the headers have a certain index public bool hasPost( string $name ) Return whether the $_POST superglobal has certain index public bool hasPut( string $name ) Return whether the PUT data has certain index public bool hasQuery( string $name ) Return whether the $_GET superglobal has certain index public bool hasServer( string $name ) Return whether the $_SERVER superglobal has certain index public bool isAjax() Return whether the request has been made using ajax. Checks if public bool isConnect() Return whether the HTTP method is CONNECT. if public bool isDelete() Return whether the HTTP method is DELETE. if public bool isGet() Return whether the HTTP method is GET. if public bool isHead() Return whether the HTTP method is HEAD. if public bool isMethod(mixed $methods,bool $strict = false) Return if the current HTTP method matches any of the passed methods public bool isOptions() Return whether the HTTP method is OPTIONS. if public bool isPost() Return whether the HTTP method is POST. if public bool isPurge() Return whether the HTTP method is PURGE (Squid and Varnish support). if public bool isPut() Return whether the HTTP method is PUT. if public bool isSecure() Return whether the request has been made using any secure layer public bool isSoap() Return whether the request has been made using SOAP public bool isTrace() Return whether the HTTP method is TRACE. public int numFiles( bool $onlySuccessful = false ) Returns the number of files available

Methods

Public · 50

get()

public function get(
    string|null $name = null,
    mixed $filters = null,
    mixed $defaultValue = null,
    bool $notAllowEmpty = false,
    bool $noRecursive = false
): mixed;

Gets a variable from the $_REQUEST superglobal applying filters if needed. If no parameters are given the $_REQUEST superglobal is returned

// Returns value from $_REQUEST["user_email"] without sanitizing
$userEmail = $request->get("user_email");

// Returns value from $_REQUEST["user_email"] with sanitizing
$userEmail = $request->get("user_email", "email");

getAcceptableContent()

public function getAcceptableContent(): array;

Return an array with mime/types and their quality accepted by the browser/client from _SERVER["HTTP_ACCEPT"]

getBasicAuth()

public function getBasicAuth(): array|null;

Gets auth info accepted by the browser/client from $_SERVER["PHP_AUTH_USER"]

getBestAccept()

public function getBestAccept(): string;

Return the best mime/type accepted by the browser/client from _SERVER["HTTP_ACCEPT"]

getBestCharset()

public function getBestCharset(): string;

Return the best charset accepted by the browser/client from _SERVER["HTTP_ACCEPT_CHARSET"]

getBestLanguage()

public function getBestLanguage(): string;

Return the best language accepted by the browser/client from _SERVER["HTTP_ACCEPT_LANGUAGE"]

getClientAddress()

public function getClientAddress( bool $trustForwardedHeader = false ): bool|string;

Return the most possible client IPv4 Address. This method searches in $_SERVER["REMOTE_ADDR"] and optionally in $_SERVER["HTTP_X_FORWARDED_FOR"]

getClientCharsets()

public function getClientCharsets(): array;

Return a charset array and their quality accepted by the browser/client from _SERVER["HTTP_ACCEPT_CHARSET"]

getContentType()

public function getContentType(): string|null;

Return the content type which request has been made

getDigestAuth()

public function getDigestAuth(): array;

Return the auth info accepted by the browser/client from $_SERVER["PHP_AUTH_DIGEST"]

getHTTPReferer()

public function getHTTPReferer(): string;

Return the web page that refers active request. ie: https://phalcon.io

getHeader()

public function getHeader( string $header ): string;

Return the HTTP header from request data

getHeaders()

public function getHeaders(): array;

Return the available headers in the request

$_SERVER = [
    "PHP_AUTH_USER" => "phalcon",
    "PHP_AUTH_PW"   => "secret",
];

$headers = $request->getHeaders();

echo $headers["Authorization"]; // Basic cGhhbGNvbjpzZWNyZXQ=

getHttpHost()

public function getHttpHost(): string;

Return the host name used by the request.

Request::getHttpHost trying to find host name in following order:

  • $_SERVER["HTTP_HOST"]
  • $_SERVER["SERVER_NAME"]
  • $_SERVER["SERVER_ADDR"]

Optionally Request::getHttpHost validates and clean host name. The Request::$strictHostCheck can be used to validate host name.

Note: validation and cleaning have a negative performance impact because they use regular expressions.

use Phalcon\Http\Request;

$request = new Request;

$_SERVER["HTTP_HOST"] = "example.com";
$request->getHttpHost(); // example.com

$_SERVER["HTTP_HOST"] = "example.com:8080";
$request->getHttpHost(); // example.com:8080

$request->setStrictHostCheck(true);
$_SERVER["HTTP_HOST"] = "ex=am~ple.com";
$request->getHttpHost(); // UnexpectedValueException

$_SERVER["HTTP_HOST"] = "ExAmPlE.com";
$request->getHttpHost(); // example.com

getJsonRawBody()

public function getJsonRawBody( bool $associative = false ): array|bool|stdClass;

Return the decoded JSON HTTP raw request body

getLanguages()

public function getLanguages(): array;

Return the languages array and their quality accepted by the browser/client from _SERVER["HTTP_ACCEPT_LANGUAGE"]

getMethod()

public function getMethod(): string;

Return the HTTP method which request has been made

If the X-HTTP-Method-Override header is set, and if the method is a POST, then it is used to determine the "real" intended HTTP method.

The _method request parameter can also be used to determine the HTTP method, but only if setHttpMethodParameterOverride(true) has been called.

The method is always an uppercased string.

getPort()

public function getPort(): int;

Return the information about the port on which the request is made

getPost()

public function getPost(
    string|null $name = null,
    mixed $filters = null,
    mixed $defaultValue = null,
    bool $notAllowEmpty = false,
    bool $noRecursive = false
): mixed;

Return a variable from the $_POST superglobal applying filters if needed. If no parameters are given the $_POST superglobal is returned

// Returns value from $_POST["user_email"] without sanitizing
$userEmail = $request->getPost("user_email");

// Returns value from $_POST["user_email"] with sanitizing
$userEmail = $request->getPost("user_email", "email");

getPut()

public function getPut(
    string|null $name = null,
    mixed $filters = null,
    mixed $defaultValue = null,
    bool $notAllowEmpty = false,
    bool $noRecursive = false
);

Return a variable from put request

// Returns value from $_PUT["user_email"] without sanitizing
$userEmail = $request->getPut("user_email");

// Returns value from $_PUT["user_email"] with sanitizing
$userEmail = $request->getPut("user_email", "email");

getQuery()

public function getQuery(
    string|null $name = null,
    mixed $filters = null,
    mixed $defaultValue = null,
    bool $notAllowEmpty = false,
    bool $noRecursive = false
);

Return a variable from $_GET superglobal applying filters if needed. If no parameters are given the $_GET superglobal is returned

// Returns value from $_GET["id"] without sanitizing
$id = $request->getQuery("id");

// Returns value from $_GET["id"] with sanitizing
$id = $request->getQuery("id", "int");

// Returns value from $_GET["id"] with a default value
$id = $request->getQuery("id", null, 150);

getRawBody()

public function getRawBody(): string;

Return the HTTP raw request body

getScheme()

public function getScheme(): string;

Return the HTTP schema (http/https)

getServer()

public function getServer( string $name ): string|null;

Return a variable from $_SERVER superglobal

getServerAddress()

public function getServerAddress(): string;

Return the active server address IP

getServerName()

public function getServerName(): string;

Return the active server name

getURI()

public function getURI( bool $onlyPath = false ): string;

Return the HTTP URI which request has been made to

// Returns /some/path?with=queryParams
$uri = $request->getURI();

// Returns /some/path
$uri = $request->getURI(true);

getUploadedFiles()

public function getUploadedFiles(
    bool $onlySuccessful = false,
    bool $namedKeys = false
): array;

Return the attached files as Phalcon\Http\Request\FileInterface compatible instances

getUserAgent()

public function getUserAgent(): string;

Return the HTTP user agent used to make the request

has()

public function has( string $name ): bool;

Return whether the $_REQUEST superglobal has certain index

hasFiles()

public function hasFiles(): bool;

Return whether the request includes attached files

hasHeader()

public function hasHeader( string $header ): bool;

Return whether the headers have a certain index

hasPost()

public function hasPost( string $name ): bool;

Return whether the $_POST superglobal has certain index

hasPut()

public function hasPut( string $name ): bool;

Return whether the PUT data has certain index

hasQuery()

public function hasQuery( string $name ): bool;

Return whether the $_GET superglobal has certain index

hasServer()

public function hasServer( string $name ): bool;

Return whether the $_SERVER superglobal has certain index

isAjax()

public function isAjax(): bool;

Return whether the request has been made using ajax. Checks if $_SERVER["HTTP_X_REQUESTED_WITH"] === "XMLHttpRequest"

isConnect()

public function isConnect(): bool;

Return whether the HTTP method is CONNECT. if $_SERVER["REQUEST_METHOD"] === "CONNECT"

isDelete()

public function isDelete(): bool;

Return whether the HTTP method is DELETE. if $_SERVER["REQUEST_METHOD"] === "DELETE"

isGet()

public function isGet(): bool;

Return whether the HTTP method is GET. if $_SERVER["REQUEST_METHOD"] === "GET"

isHead()

public function isHead(): bool;

Return whether the HTTP method is HEAD. if $_SERVER["REQUEST_METHOD"] === "HEAD"

isMethod()

public function isMethod(
    mixed $methods,
    bool $strict = false
): bool;

Return if the current HTTP method matches any of the passed methods

isOptions()

public function isOptions(): bool;

Return whether the HTTP method is OPTIONS. if $_SERVER["REQUEST_METHOD"] === "OPTIONS"

isPost()

public function isPost(): bool;

Return whether the HTTP method is POST. if $_SERVER["REQUEST_METHOD"] === "POST"

isPurge()

public function isPurge(): bool;

Return whether the HTTP method is PURGE (Squid and Varnish support). if $_SERVER["REQUEST_METHOD"] === "PURGE"

isPut()

public function isPut(): bool;

Return whether the HTTP method is PUT. if $_SERVER["REQUEST_METHOD"] === "PUT"

isSecure()

public function isSecure(): bool;

Return whether the request has been made using any secure layer

isSoap()

public function isSoap(): bool;

Return whether the request has been made using SOAP

isTrace()

public function isTrace(): bool;

Return whether the HTTP method is TRACE. if $_SERVER["REQUEST_METHOD"] === "TRACE"

numFiles()

public function numFiles( bool $onlySuccessful = false ): int;

Returns the number of files available

Http\Request\Bag\AbstractBag

Abstract Source on GitHub

Shared base for the HTTP request bags. A bag is a string- or integer-keyed value store backed by a raw array, exposing get/has/set/remove/all plus typed readers for cast-with-default access.

Two protected hooks (normalizeKey, normalizeItems) let subclasses change key handling without restating the surface.

The ArrayAccess append form ($bag[] = $value) is rejected with a NullKeyException: the append form supplies no explicit key, so the write could never be addressed by the caller.

Uses ArrayAccess · ArrayIterator · Countable · IteratorAggregate · Phalcon\Http\Request\Exceptions\NullKeyException · Traversable

Method Summary

public __construct( array $items = [] ) AbstractBag constructor. public array all() Returns all the elements of the bag public int count() Returns the number of elements in the bag public mixed get(int|string $key,mixed $defaultValue = null) Returns an element of the bag, or the default value if it is not set public array getArray(int|string $key,array $defaultValue = []) Returns an element of the bag as an array. The default value is public bool getBool(int|string $key,bool $defaultValue = false) Returns an element of the bag cast to bool, or the default value if public float getFloat(int|string $key,float $defaultValue = 0) Returns an element of the bag cast to float, or the default value if public int getInt(int|string $key,int $defaultValue = 0) Returns an element of the bag cast to int, or the default value if public Traversable getIterator() Returns the iterator of the bag public string getString(int|string $key,string $defaultValue = "") Returns an element of the bag cast to string, or the default value if public bool has( int|string $key ) Checks whether an element exists in the bag public bool offsetExists( mixed $offset ) Whether an offset exists public mixed offsetGet( mixed $offset ) Offset to retrieve public void offsetSet(mixed $offset,mixed $value) Offset to set public void offsetUnset( mixed $offset ) Offset to unset public void remove( int|string $key ) Removes an element from the bag public void set(int|string $key,mixed $value) Sets an element in the bag protected array normalizeItems( array $items ) Normalizes the items at construction time. Identity in the base; protected int|string normalizeKey( int|string $key ) Normalizes a key for lookups and writes. Identity in the base;

Properties

protected array $items

Methods

Public · 17

__construct()

public function __construct( array $items = [] );

AbstractBag constructor.

all()

public function all(): array;

Returns all the elements of the bag

count()

public function count(): int;

Returns the number of elements in the bag

get()

public function get(
    int|string $key,
    mixed $defaultValue = null
): mixed;

Returns an element of the bag, or the default value if it is not set

getArray()

public function getArray(
    int|string $key,
    array $defaultValue = []
): array;

Returns an element of the bag as an array. The default value is returned if the element is not set or is not an array

getBool()

public function getBool(
    int|string $key,
    bool $defaultValue = false
): bool;

Returns an element of the bag cast to bool, or the default value if it is not set

getFloat()

public function getFloat(
    int|string $key,
    float $defaultValue = 0
): float;

Returns an element of the bag cast to float, or the default value if it is not set

getInt()

public function getInt(
    int|string $key,
    int $defaultValue = 0
): int;

Returns an element of the bag cast to int, or the default value if it is not set

getIterator()

public function getIterator(): Traversable;

Returns the iterator of the bag

getString()

public function getString(
    int|string $key,
    string $defaultValue = ""
): string;

Returns an element of the bag cast to string, or the default value if it is not set

has()

public function has( int|string $key ): bool;

Checks whether an element exists in the bag

offsetExists()

public function offsetExists( mixed $offset ): bool;

Whether an offset exists

@link https://php.net/manual/en/arrayaccess.offsetexists.php

offsetGet()

public function offsetGet( mixed $offset ): mixed;

Offset to retrieve

@link https://php.net/manual/en/arrayaccess.offsetget.php

offsetSet()

public function offsetSet(
    mixed $offset,
    mixed $value
): void;

Offset to set

@link https://php.net/manual/en/arrayaccess.offsetset.php

offsetUnset()

public function offsetUnset( mixed $offset ): void;

Offset to unset

@link https://php.net/manual/en/arrayaccess.offsetunset.php

remove()

public function remove( int|string $key ): void;

Removes an element from the bag

set()

public function set(
    int|string $key,
    mixed $value
): void;

Sets an element in the bag

Protected · 2

normalizeItems()

protected function normalizeItems( array $items ): array;

Normalizes the items at construction time. Identity in the base; subclasses can override it to normalize keys

normalizeKey()

protected function normalizeKey( int|string $key ): int|string;

Normalizes a key for lookups and writes. Identity in the base; subclasses can override it to change key handling

Http\Request\Bag\AttributeBag

Class Source on GitHub

Holds the request attributes: arbitrary, application-defined values attached to the request during its lifecycle (router, dispatcher, security components etc.). Unlike the other request bags, it is not hydrated from a superglobal - it always starts empty.

The base class supplies the entire surface; this class exists as a distinct type so DI typing and IDE autocomplete stay precise.

Http\Request\Exception

Class Source on GitHub

Phalcon\Http\Request\Exception

Exceptions thrown in Phalcon\Http\Request will use this class

Http\Request\Exceptions\FilterServiceUnavailable

Class Source on GitHub

Uses Phalcon\Http\Request\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Http\Request\Exceptions\InvalidHost

Class Source on GitHub

  • \UnexpectedValueException
    • Phalcon\Http\Request\Exceptions\InvalidHost

Uses UnexpectedValueException

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $host );

Http\Request\Exceptions\InvalidHttpMethod

Class Source on GitHub

Uses Phalcon\Http\Request\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $method );

Http\Request\Exceptions\MissingFilters

Class Source on GitHub

Uses Phalcon\Http\Request\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $name );

Http\Request\Exceptions\NullKeyException

Class Source on GitHub

Thrown by AbstractBag::offsetSet() when a null offset is used (the ArrayAccess append form). Bags are always string-keyed, so an auto-indexed write could never be addressed by the caller.

Uses Phalcon\Http\Request\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Http\Request\Exceptions\SanitizerNotFound

Class Source on GitHub

Uses Phalcon\Http\Request\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $sanitizer );

Http\Request\File

Class Source on GitHub

Phalcon\Http\Request\File

Provides OO wrappers to the $_FILES superglobal

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function uploadAction()
    {
        // Check if the user has uploaded files
        if ($this->request->hasFiles() == true) {
            // Print the real file names and their sizes
            foreach ($this->request->getUploadedFiles() as $file) {
                echo $file->getName(), " ", $file->getSize(), "\n";
            }
        }
    }
}

Uses Phalcon\Traits\Support\Helper\Arr\GetTrait

Method Summary

Properties

protected int $error = 0
protected string $extension = ""
protected string $key = ""
protected string $name = ""
protected string $realType
protected int $size = 0
protected string $tmpName = ""
protected string $type = ""

Methods

Public · 11

__construct()

public function __construct(
    array $file,
    string $key = ""
);

Constructor

getError()

public function getError(): int;

getExtension()

public function getExtension(): string;

getKey()

public function getKey(): string;

getName()

public function getName(): string;

Returns the real name of the uploaded file

getRealType()

public function getRealType(): string;

Gets the real mime type of the upload file using finfo

getSize()

public function getSize(): int;

Returns the file size of the uploaded file

getTempName()

public function getTempName(): string;

Returns the temporary name of the uploaded file

getType()

public function getType(): string;

Returns the mime type reported by the browser This mime type is not completely secure, use getRealType() instead

isUploadedFile()

public function isUploadedFile(): bool;

Checks whether the file has been uploaded via Post.

moveTo()

public function moveTo( string $destination ): bool;

Moves the temporary file to a destination within the application

Http\Request\FileInterface

Interface Source on GitHub

Interface for Phalcon\Http\Request\File

  • Phalcon\Http\Request\FileInterface

Method Summary

Methods

Public · 7

getError()

public function getError(): int;

Returns the error if any

getName()

public function getName(): string;

Returns the real name of the uploaded file

getRealType()

public function getRealType(): string;

Gets the real mime type of the upload file using finfo

getSize()

public function getSize(): int;

Returns the file size of the uploaded file

getTempName()

public function getTempName(): string;

Returns the temporal name of the uploaded file

getType()

public function getType(): string;

Returns the mime type reported by the browser This mime type is not completely secure, use getRealType() instead

moveTo()

public function moveTo( string $destination ): bool;

Move the temporary file to a destination

Http\Response

Class Source on GitHub

Part of the HTTP cycle is return responses to the clients. Phalcon\HTTP\Response is the Phalcon component responsible to achieve this task. HTTP responses are usually composed by headers and body.

$response = new \Phalcon\Http\Response();

$response->setStatusCode(200, "OK");
$response->setContent("<html><body>Hello</body></html>");

$response->send();

Uses DateTime · DateTimeZone · Phalcon\Di\Di · Phalcon\Di\DiInterface · Phalcon\Di\Injectable · Phalcon\Events\EventsAwareInterface · Phalcon\Events\Exception · Phalcon\Events\Traits\EventsAwareTrait · Phalcon\Http\Message\Interfaces\ResponseStatusCodeInterface · Phalcon\Http\Message\ResponseStatusCodeInterface · Phalcon\Http\Response\CookiesInterface · Phalcon\Http\Response\Exception · Phalcon\Http\Response\Exceptions\NonStandardStatusCodeRequiresMessage · Phalcon\Http\Response\Exceptions\ResponseAlreadySent · Phalcon\Http\Response\Exceptions\UrlServiceUnavailable · Phalcon\Http\Response\Headers · Phalcon\Http\Response\HeadersInterface · Phalcon\Http\Traits\StatusPhrasesTrait · Phalcon\Mvc\Url\UrlInterface · Phalcon\Mvc\ViewInterface · Phalcon\Support\Helper\File\Basename · Phalcon\Support\Helper\Json\Encode · Phalcon\Traits\Php\InfoTrait · Phalcon\Traits\Php\UrlTrait

Method Summary

public __construct(string|null $content = null,int|null $code = null,string|null $status = null) Constructor public ResponseInterface appendContent( mixed $content ) Appends a string to the HTTP response body public string getContent() Gets the HTTP response body public CookiesInterface getCookies() Returns cookies set by the user public DiInterface getDI() Returns the internal dependency injector public HeadersInterface getHeaders() Returns headers set by the user public string|null getReasonPhrase() Returns the reason phrase public int|null getStatusCode() Returns the status code public bool hasHeader( string $name ) Checks if a header exists public bool isSent() Check if the response is already sent public ResponseInterface redirect(string|null $location = null,bool $externalRedirect = false,int $statusCode = 302) Redirect by HTTP to another action or URL public ResponseInterface removeHeader( string $name ) Remove a header in the response public ResponseInterface resetHeaders() Resets all the established headers public ResponseInterface send() Prints out HTTP response to the client public ResponseInterface sendCookies() Sends cookies to the client public bool|ResponseInterface sendHeaders() Sends headers to the client public ResponseInterface setCache( int $minutes ) Sets Cache headers to use HTTP cache public ResponseInterface setContent( string $content ) Sets HTTP response body public ResponseInterface setContentLength( int $contentLength ) Sets the response content-length public ResponseInterface setContentType(string $contentType,string|null $charset = null) Sets the response content-type mime, optionally the charset public ResponseInterface setCookies( CookiesInterface $cookies ) Sets a cookies bag for the response externally public ResponseInterface setEtag( string $etag ) Set a custom ETag public ResponseInterface setExpires( DateTime $datetime ) Sets an Expires header in the response that allows to use the HTTP cache public ResponseInterface setFileToSend(string $filePath,string|null $attachmentName = null,bool $attachment = true) Sets an attached file to be sent at the end of the request public ResponseInterface setHeader(string $name,mixed $value) Overwrites a header in the response public ResponseInterface setHeaders( HeadersInterface $headers ) Sets a headers bag for the response externally public ResponseInterface setJsonContent(mixed $content,int $jsonOptions = 0,int $depth = 512) Sets HTTP response body. The parameter is automatically converted to public ResponseInterface setLastModified( DateTime $datetime ) Sets Last-Modified header public ResponseInterface setNotModified() Sends a Not-Modified response public ResponseInterface setRawHeader( string $header ) Send a raw header to the response public ResponseInterface setStatusCode(int $code,string|null $message = null) Sets the HTTP response code

Constants

string DATETIME_FORMAT = "D, d M Y H:i:s"

Properties

protected string|null $content = null
protected CookiesInterface|null $cookies = null
protected Encode $encode
protected string|null $file = null
protected Headers $headers
protected bool $sent = false

Methods

Public · 31

__construct()

public function __construct(
    string|null $content = null,
    int|null $code = null,
    string|null $status = null
);

Constructor

appendContent()

public function appendContent( mixed $content ): ResponseInterface;

Appends a string to the HTTP response body

getContent()

public function getContent(): string;

Gets the HTTP response body

getCookies()

public function getCookies(): CookiesInterface;

Returns cookies set by the user

getDI()

public function getDI(): DiInterface;

Returns the internal dependency injector

getHeaders()

public function getHeaders(): HeadersInterface;

Returns headers set by the user

getReasonPhrase()

public function getReasonPhrase(): string|null;

Returns the reason phrase

echo $response->getReasonPhrase();

getStatusCode()

public function getStatusCode(): int|null;

Returns the status code

echo $response->getStatusCode();

hasHeader()

public function hasHeader( string $name ): bool;

Checks if a header exists

$response->hasHeader("Content-Type");

isSent()

public function isSent(): bool;

Check if the response is already sent

redirect()

public function redirect(
    string|null $location = null,
    bool $externalRedirect = false,
    int $statusCode = 302
): ResponseInterface;

Redirect by HTTP to another action or URL

// Using a string redirect (internal/external)
$response->redirect("posts/index");
$response->redirect("https://en.wikipedia.org", true);
$response->redirect("http://www.example.com/new-location", true, 301);

// Making a redirection based on a named route
$response->redirect(
    [
        "for"        => "index-lang",
        "lang"       => "jp",
        "controller" => "index",
    ]
);

removeHeader()

public function removeHeader( string $name ): ResponseInterface;

Remove a header in the response

$response->removeHeader("Expires");

resetHeaders()

public function resetHeaders(): ResponseInterface;

Resets all the established headers

send()

public function send(): ResponseInterface;

Prints out HTTP response to the client

sendCookies()

public function sendCookies(): ResponseInterface;

Sends cookies to the client

sendHeaders()

public function sendHeaders(): bool|ResponseInterface;

Sends headers to the client

setCache()

public function setCache( int $minutes ): ResponseInterface;

Sets Cache headers to use HTTP cache

$this->response->setCache(60);

setContent()

public function setContent( string $content ): ResponseInterface;

Sets HTTP response body

$response->setContent("<h1>Hello!</h1>");

setContentLength()

public function setContentLength( int $contentLength ): ResponseInterface;

Sets the response content-length

$response->setContentLength(2048);

setContentType()

public function setContentType(
    string $contentType,
    string|null $charset = null
): ResponseInterface;

Sets the response content-type mime, optionally the charset

$response->setContentType("application/pdf");
$response->setContentType("text/plain", "UTF-8");

setCookies()

public function setCookies( CookiesInterface $cookies ): ResponseInterface;

Sets a cookies bag for the response externally

setEtag()

public function setEtag( string $etag ): ResponseInterface;

Set a custom ETag

$response->setEtag(
    md5(
        time()
    )
);

setExpires()

public function setExpires( DateTime $datetime ): ResponseInterface;

Sets an Expires header in the response that allows to use the HTTP cache

$this->response->setExpires(
    new DateTime()
);

setFileToSend()

public function setFileToSend(
    string $filePath,
    string|null $attachmentName = null,
    bool $attachment = true
): ResponseInterface;

Sets an attached file to be sent at the end of the request

setHeader()

public function setHeader(
    string $name,
    mixed $value
): ResponseInterface;

Overwrites a header in the response

$response->setHeader("Content-Type", "text/plain");

setHeaders()

public function setHeaders( HeadersInterface $headers ): ResponseInterface;

Sets a headers bag for the response externally

setJsonContent()

public function setJsonContent(
    mixed $content,
    int $jsonOptions = 0,
    int $depth = 512
): ResponseInterface;

Sets HTTP response body. The parameter is automatically converted to JSON and also sets default header: Content-Type: "application/json; charset=UTF-8"

$response->setJsonContent(
    [
        "status" => "OK",
    ]
);

setLastModified()

public function setLastModified( DateTime $datetime ): ResponseInterface;

Sets Last-Modified header

$this->response->setLastModified(
    new DateTime()
);

setNotModified()

public function setNotModified(): ResponseInterface;

Sends a Not-Modified response

setRawHeader()

public function setRawHeader( string $header ): ResponseInterface;

Send a raw header to the response

$response->setRawHeader("HTTP/1.1 404 Not Found");

setStatusCode()

public function setStatusCode(
    int $code,
    string|null $message = null
): ResponseInterface;

Sets the HTTP response code

$response->setStatusCode(404, "Not Found");

Http\ResponseInterface

Interface Source on GitHub

Phalcon\Http\Response

Interface for Phalcon\Http\Response

  • Phalcon\Http\ResponseInterface

Uses DateTime · Phalcon\Http\Response\HeadersInterface

Method Summary

public ResponseInterface appendContent( string $content ) Appends a string to the HTTP response body public string getContent() Gets the HTTP response body public HeadersInterface getHeaders() Returns headers set by the user public int|null getStatusCode() Returns the status code public bool hasHeader( string $name ) Checks if a header exists public bool isSent() Checks if the response was already sent public ResponseInterface redirect(string|null $location = null,bool $externalRedirect = false,int $statusCode = 302) Redirect by HTTP to another action or URL public ResponseInterface resetHeaders() Resets all the established headers public ResponseInterface send() Prints out HTTP response to the client public ResponseInterface sendCookies() Sends cookies to the client public bool|ResponseInterface sendHeaders() Sends headers to the client public ResponseInterface setContent( string $content ) Sets HTTP response body public ResponseInterface setContentLength( int $contentLength ) Sets the response content-length public ResponseInterface setContentType(string $contentType,string|null $charset = null) Sets the response content-type mime, optionally the charset public ResponseInterface setExpires( DateTime $datetime ) Sets output expire time header public ResponseInterface setFileToSend(string $filePath,string|null $attachmentName = null) Sets an attached file to be sent at the end of the request public ResponseInterface setHeader(string $name,string $value) Overwrites a header in the response public ResponseInterface setJsonContent( mixed $content ) Sets HTTP response body. The parameter is automatically converted to JSON public ResponseInterface setNotModified() Sends a Not-Modified response public ResponseInterface setRawHeader( string $header ) Send a raw header to the response public ResponseInterface setStatusCode(int $code,string|null $message = null) Sets the HTTP response code

Methods

Public · 21

appendContent()

public function appendContent( string $content ): ResponseInterface;

Appends a string to the HTTP response body

getContent()

public function getContent(): string;

Gets the HTTP response body

getHeaders()

public function getHeaders(): HeadersInterface;

Returns headers set by the user

getStatusCode()

public function getStatusCode(): int|null;

Returns the status code

hasHeader()

public function hasHeader( string $name ): bool;

Checks if a header exists

isSent()

public function isSent(): bool;

Checks if the response was already sent

redirect()

public function redirect(
    string|null $location = null,
    bool $externalRedirect = false,
    int $statusCode = 302
): ResponseInterface;

Redirect by HTTP to another action or URL

resetHeaders()

public function resetHeaders(): ResponseInterface;

Resets all the established headers

send()

public function send(): ResponseInterface;

Prints out HTTP response to the client

sendCookies()

public function sendCookies(): ResponseInterface;

Sends cookies to the client

sendHeaders()

public function sendHeaders(): bool|ResponseInterface;

Sends headers to the client

setContent()

public function setContent( string $content ): ResponseInterface;

Sets HTTP response body

setContentLength()

public function setContentLength( int $contentLength ): ResponseInterface;

Sets the response content-length

setContentType()

public function setContentType(
    string $contentType,
    string|null $charset = null
): ResponseInterface;

Sets the response content-type mime, optionally the charset

setExpires()

public function setExpires( DateTime $datetime ): ResponseInterface;

Sets output expire time header

setFileToSend()

public function setFileToSend(
    string $filePath,
    string|null $attachmentName = null
): ResponseInterface;

Sets an attached file to be sent at the end of the request

setHeader()

public function setHeader(
    string $name,
    string $value
): ResponseInterface;

Overwrites a header in the response

setJsonContent()

public function setJsonContent( mixed $content ): ResponseInterface;

Sets HTTP response body. The parameter is automatically converted to JSON

$response->setJsonContent(
    [
        "status" => "OK",
    ]
);

setNotModified()

public function setNotModified(): ResponseInterface;

Sends a Not-Modified response

setRawHeader()

public function setRawHeader( string $header ): ResponseInterface;

Send a raw header to the response

setStatusCode()

public function setStatusCode(
    int $code,
    string|null $message = null
): ResponseInterface;

Sets the HTTP response code

Http\Response\Cookies

Class Source on GitHub

This class is a bag to manage the cookies.

A cookies bag is automatically registered as part of the 'response' service in the DI. By default, cookies are automatically encrypted before being sent to the client and are decrypted when retrieved from the user. To set sign key used to generate a message authentication code use Phalcon\Http\Response\Cookies::setSignKey().

use Phalcon\Di\Di;
use Phalcon\Encryption\Crypt;
use Phalcon\Http\Response\Cookies;

$di = new Di();

$di->set(
    'crypt',
    function () {
        $crypt = new Crypt();

        // The `$key' should have been previously generated in a
        // cryptographically safe way.
        $key =
        "T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3";

        $crypt->setKey($key);

        return $crypt;
    }
);

$di->set(
    'cookies',
    function () {
        $cookies = new Cookies();

        // The `$key' MUST be at least 32 characters long and generated
        // using a cryptographically secure pseudo random generator.
        $key =
        "#1dj8$=dp?.ak//j1V$~%*0XaK\xb1\x8d\xa9\x98\x054t7w!z%C*F-Jk\x98\x05\\\x5c";

        $cookies->setSignKey($key);

        return $cookies;
    }
);

Uses Phalcon\Di\AbstractInjectionAware · Phalcon\Di\DiInterface · Phalcon\Http\Cookie\CookieInterface · Phalcon\Http\Cookie\Exception · Phalcon\Http\Response\Exceptions\ResponseServiceUnavailable · Phalcon\Http\Traits\EncryptionAwareTrait

Method Summary

Properties

protected array $cookies = []
protected bool $isRegistered = false
protected bool $isSent = false
protected string|null $signKey = null The cookie's sign key.

Methods

Public · 11

__construct()

public function __construct(
    bool $useEncryption = true,
    string|null $signKey = null
);

Constructor

delete()

public function delete( string $name ): bool;

Deletes a cookie by its name This method does not remove cookies from the _COOKIE super-global

get()

public function get( string $name ): CookieInterface;

Gets a cookie from the bag

getCookies()

public function getCookies(): array;

Gets all cookies from the bag

has()

public function has( string $name ): bool;

Check if a cookie is defined in the bag or exists in the _COOKIE super-global

isSent()

public function isSent(): bool;

Returns if the headers have already been sent

reset()

public function reset(): CookiesInterface;

Reset set cookies

send()

public function send(): bool;

Sends the cookies to the client Cookies aren't sent if headers are sent in the current request

set()

public function set(
    string $name,
    mixed $value = null,
    int $expire = 0,
    string $path = "/",
    bool $secure = false,
    string $domain = "",
    bool $httpOnly = false,
    array $options = []
): CookiesInterface;

Sets a cookie to be sent at the end of the request.

This method overrides any cookie set before with the same name.

use Phalcon\Http\Response\Cookies;

$now = new DateTimeImmutable();
$tomorrow = $now->modify('tomorrow');

$cookies = new Cookies();
$cookies->set(
    'remember-me',
    json_encode(['user_id' => 1]),
    (int) $tomorrow->format('U'),
);

setSignKey()

public function setSignKey( string|null $signKey = null ): CookiesInterface;

Sets the cookie's sign key.

The `$signKey' MUST be at least 32 characters long and generated using a cryptographically secure pseudo random generator.

Use NULL to disable cookie signing.

useEncryption()

public function useEncryption( bool $useEncryption ): CookiesInterface;

Set if cookies in the bag must be automatically encrypted/decrypted

Protected · 1

checkGetContainer()

protected function checkGetContainer(): DiInterface;

Http\Response\CookiesInterface

Interface Source on GitHub

Interface for Phalcon\Http\Response\Cookies

  • Phalcon\Http\Response\CookiesInterface

Uses Phalcon\Http\Cookie\CookieInterface

Method Summary

Methods

Public · 8

delete()

public function delete( string $name ): bool;

Deletes a cookie by its name This method does not remove cookies from the _COOKIE superglobal

get()

public function get( string $name ): CookieInterface;

Gets a cookie from the bag

has()

public function has( string $name ): bool;

Check if a cookie is defined in the bag or exists in the _COOKIE superglobal

isUsingEncryption()

public function isUsingEncryption(): bool;

Returns if the bag is automatically encrypting/decrypting cookies

reset()

public function reset(): CookiesInterface;

Reset set cookies

send()

public function send(): bool;

Sends the cookies to the client

set()

public function set(
    string $name,
    mixed $value = null,
    int $expire = 0,
    string $path = "/",
    bool $secure = false,
    string $domain = "",
    bool $httpOnly = false,
    array $options = []
): CookiesInterface;

Sets a cookie to be sent at the end of the request

useEncryption()

public function useEncryption( bool $useEncryption ): CookiesInterface;

Set if cookies in the bag must be automatically encrypted/decrypted

Http\Response\Exception

Class Source on GitHub

Phalcon\Http\Response\Exception

Exceptions thrown in Phalcon\Http\Response will use this class.

Http\Response\Exceptions\NonStandardStatusCodeRequiresMessage

Class Source on GitHub

Uses Phalcon\Http\Response\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Http\Response\Exceptions\ResponseAlreadySent

Class Source on GitHub

Uses Phalcon\Http\Response\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Http\Response\Exceptions\ResponseServiceUnavailable

Class Source on GitHub

Uses Phalcon\Http\Response\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Http\Response\Exceptions\UrlServiceUnavailable

Class Source on GitHub

Uses Phalcon\Http\Response\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Http\Response\Headers

Class Source on GitHub

This class is a bag to manage the response headers

Uses IteratorAggregate · Traversable

Method Summary

Properties

protected array $headers = []
protected bool $isSent = false

Methods

Public · 10

get()

public function get( string $name ): bool|string|null;

Gets a header value from the internal bag

getIterator()

public function getIterator(): Traversable;

has()

public function has( string $name ): bool;

Checks if a header exists

isSent()

public function isSent(): bool;

Returns if the headers have already been sent

remove()

public function remove( string $name ): HeadersInterface;

Removes a header by its name

reset()

public function reset(): void;

Reset set headers

send()

public function send(): bool;

Sends the headers to the client

set()

public function set(
    string $name,
    string $value
): HeadersInterface;

Sets a header to be sent at the end of the request

setRaw()

public function setRaw( string $header ): HeadersInterface;

Sets a raw header to be sent at the end of the request

toArray()

public function toArray(): array;

Returns the current headers as an array

Http\Response\HeadersInterface

Interface Source on GitHub

Interface for Phalcon\Http\Response\Headers compatible bags

  • Phalcon\Http\Response\HeadersInterface

Method Summary

Methods

Public · 6

get()

public function get( string $name ): bool|string|null;

Gets a header value from the internal bag

has()

public function has( string $name ): bool;

Checks if a header exists

reset()

public function reset(): void;

Reset set headers

send()

public function send(): bool;

Sends the headers to the client

set()

public function set(
    string $name,
    string $value
): HeadersInterface;

Sets a header to be sent at the end of the request

setRaw()

public function setRaw( string $header ): HeadersInterface;

Sets a raw header to be sent at the end of the request

Http\Traits\EncryptionAwareTrait

Trait Source on GitHub

Provides the implicit encryption flag and its accessor shared by the HTTP cookie classes.

  • Phalcon\Http\Traits\EncryptionAwareTrait

Used by Phalcon\Http\Cookie · Phalcon\Http\Response\Cookies

Method Summary

Properties

protected bool $useEncryption = false

Methods

Public · 1

isUsingEncryption()

public function isUsingEncryption(): bool;

Check if implicit encryption is being used

Http\Traits\StatusPhrasesTrait

Trait Source on GitHub

Status Phrases trait

  • Phalcon\Http\Traits\StatusPhrasesTrait

Uses Phalcon\Http\Message\Interfaces\ResponseStatusCodeInterface

Used by Phalcon\Http\Message\Response · Phalcon\Http\Response

Method Summary

Methods

Protected · 1

getPhrases()

protected function getPhrases(): array;

Returns the list of status codes available