Http\Cookie
ClassSource on GitHubProvide OO wrappers to manage a HTTP cookie.
\stdClassPhalcon\Di\AbstractInjectionAwarePhalcon\Http\Cookie- implementsPhalcon\Http\Cookie\CookieInterface,\Stringable
Uses Phalcon\Contracts\Http\HttpTypes · 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.
publicstring__toString()Magic __toString method converts the cookie’s value to string
publicvoiddelete()Deletes the cookie by setting an expiration time in the past
publicstringgetDomain()Returns the domain that the cookie is available to
publicintgetExpiration()Returns the current expiration time
publicboolgetHttpOnly()Returns if the cookie is accessible only through the HTTP protocol
publicstringgetName()Returns the current cookie’s name
publicarraygetOptions()Returns the current cookie’s options
publicstringgetPath()Returns the current cookie’s path
publicboolgetSecure()Returns whether the cookie must only be sent when the connection is
publicmixedgetValue(mixed $filters = null,mixed $defaultValue = null)Returns the cookie’s value.
publicCookieInterfacerestore()Reads the cookie-related info from the SESSION to restore the cookie as
publicCookieInterfacesend()Sends the cookie to the HTTP client.
publicCookieInterfacesetDomain(string $domain)Sets the domain that the cookie is available to
publicCookieInterfacesetExpiration(int $expire)Sets the cookie’s expiration time
publicCookieInterfacesetHttpOnly(bool $httpOnly)Sets if the cookie is accessible only through the HTTP protocol
publicCookieInterfacesetOptions(array $options)Sets the cookie’s options
publicCookieInterfacesetPath(string $path)Sets the cookie’s path
publicCookieInterfacesetSecure(bool $secure)Sets if the cookie must only be sent when the connection is secure
publicCookieInterfacesetSignKey(string|null $signKey = null)Sets the cookie’s sign key.
publicCookieInterfacesetValue(mixed $value)Sets the cookie’s value
publicCookieInterfaceuseEncryption(bool $useEncryption)Sets if the cookie must be encrypted/decrypted automatically
protectedvoidassertSignKeyIsLongEnough(string $signKey)Assert the cookie’s key is enough long.
Properties
protectedstring$domain = ""protectedint$expire = 0protectedFilterInterface|null$filter = nullprotectedbool$httpOnly = falseprotectedbool$isRead = falseprotectedbool$isRestored = falseprotectedstring$nameprotectedarray$options = []protectedstring$path = "/"protectedbool$secure = falseprotectedstring|null$signKey = nullThe cookie’s sign key.
protectedmixed$value = nullMethods
__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.
@todo filters needs to be array/string
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.
@see \Phalcon\Encryption\Security\Random
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
assertSignKeyIsLongEnough()
protected function assertSignKeyIsLongEnough( string $signKey ): void;Assert the cookie’s key is enough long.
Http\Cookie\CookieInterface
InterfaceSource on GitHubInterface for Phalcon\Http\Cookie
Phalcon\Http\Cookie\CookieInterface
Uses Phalcon\Contracts\Http\HttpTypes
Method Summary
publicvoiddelete()Deletes the cookie
publicstringgetDomain()Returns the domain that the cookie is available to
publicintgetExpiration()Returns the current expiration time
publicboolgetHttpOnly()Returns if the cookie is accessible only through the HTTP protocol
publicstringgetName()Returns the current cookie’s name
publicarraygetOptions()Returns the current cookie’s options
publicstringgetPath()Returns the current cookie’s path
publicboolgetSecure()Returns whether the cookie must only be sent when the connection is
publicmixedgetValue(mixed $filters = null,mixed $defaultValue = null)Returns the cookie’s value.
publicboolisUsingEncryption()Check if the cookie is using implicit encryption
publicCookieInterfacesend()Sends the cookie to the HTTP client
publicCookieInterfacesetDomain(string $domain)Sets the domain that the cookie is available to
publicCookieInterfacesetExpiration(int $expire)Sets the cookie’s expiration time
publicCookieInterfacesetHttpOnly(bool $httpOnly)Sets if the cookie is accessible only through the HTTP protocol
publicCookieInterfacesetOptions(array $options)Sets the cookie’s options
publicCookieInterfacesetPath(string $path)Sets the cookie’s expiration time
publicCookieInterfacesetSecure(bool $secure)Sets if the cookie must only be sent when the connection is secure
publicCookieInterfacesetValue(mixed $value)Sets the cookie’s value
publicCookieInterfaceuseEncryption(bool $useEncryption)Sets if the cookie must be encrypted/decrypted automatically
Methods
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.
@todo check if $filters can be more type specific
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
@todo check if we can make this a string
useEncryption()
public function useEncryption( bool $useEncryption ): CookieInterface;Sets if the cookie must be encrypted/decrypted automatically
Http\Cookie\Exception
ClassSource on GitHubPhalcon\Http\Cookie\Exception
Exceptions thrown in Phalcon\Http\Cookie will use this class.
Http\Cookie\Exceptions\CookieKeyTooShort
ClassSource on GitHub\ExceptionPhalcon\Http\Cookie\ExceptionPhalcon\Http\Cookie\Exceptions\CookieKeyTooShort
Uses Phalcon\Http\Cookie\Exception
Method Summary
Methods
__construct()
public function __construct( int $length );Http\Cookie\Exceptions\CryptInterfaceRequired
ClassSource on GitHub\ExceptionPhalcon\Http\Cookie\ExceptionPhalcon\Http\Cookie\Exceptions\CryptInterfaceRequired
Uses Phalcon\Http\Cookie\Exception
Method Summary
Methods
__construct()
public function __construct();Http\Cookie\Exceptions\CryptServiceUnavailable
ClassSource on GitHub\ExceptionPhalcon\Http\Cookie\ExceptionPhalcon\Http\Cookie\Exceptions\CryptServiceUnavailable
Uses Phalcon\Http\Cookie\Exception
Method Summary
Methods
__construct()
public function __construct();Http\Cookie\Exceptions\FilterServiceUnavailable
ClassSource on GitHub\ExceptionPhalcon\Http\Cookie\ExceptionPhalcon\Http\Cookie\Exceptions\FilterServiceUnavailable
Uses Phalcon\Http\Cookie\Exception
Method Summary
Methods
__construct()
public function __construct();Http\Message\RequestMethodInterface
InterfaceSource on GitHubInterface 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\RequestMethodInterface
Constants
stringMETHOD_CONNECT = "CONNECT"stringMETHOD_DELETE = "DELETE"stringMETHOD_GET = "GET"stringMETHOD_HEAD = "HEAD"stringMETHOD_OPTIONS = "OPTIONS"stringMETHOD_PATCH = "PATCH"stringMETHOD_POST = "POST"stringMETHOD_PURGE = "PURGE"stringMETHOD_PUT = "PUT"stringMETHOD_TRACE = "TRACE"Http\Message\ResponseStatusCodeInterface
InterfaceSource on GitHubInterface 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
Phalcon\Http\Message\ResponseStatusCodeInterface
Constants
intSTATUS_ACCEPTED = 202intSTATUS_ALREADY_REPORTED = 208intSTATUS_BAD_GATEWAY = 502intSTATUS_BAD_REQUEST = 400intSTATUS_BANDWIDTH_LIMIT_EXCEEDED = 509intSTATUS_BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS = 450intSTATUS_CLIENT_CLOSED_REQUEST = 499intSTATUS_CONFLICT = 409intSTATUS_CONNECTION_TIMEOUT = 522intSTATUS_CONTINUE = 100intSTATUS_CREATED = 201intSTATUS_EARLY_HINTS = 103intSTATUS_EXPECTATION_FAILED = 417intSTATUS_FAILED_DEPENDENCY = 424intSTATUS_FORBIDDEN = 403intSTATUS_FOUND = 302intSTATUS_GATEWAY_TIMEOUT = 504intSTATUS_GONE = 410intSTATUS_HTTP_REQUEST_SENT_TO_HTTPS_PORT = 497intSTATUS_IM_A_TEAPOT = 418intSTATUS_IM_USED = 226intSTATUS_INSUFFICIENT_STORAGE = 507intSTATUS_INTERNAL_SERVER_ERROR = 500intSTATUS_INVALID_SSL_CERTIFICATE = 526intSTATUS_INVALID_TOKEN_ESRI = 498intSTATUS_LENGTH_REQUIRED = 411intSTATUS_LOCKED = 423intSTATUS_LOGIN_TIMEOUT = 440intSTATUS_LOOP_DETECTED = 508intSTATUS_METHOD_FAILURE = 420intSTATUS_METHOD_NOT_ALLOWED = 405intSTATUS_MISDIRECTED_REQUEST = 421intSTATUS_MOVED_PERMANENTLY = 301intSTATUS_MULTIPLE_CHOICES = 300intSTATUS_MULTI_STATUS = 207intSTATUS_NETWORK_AUTHENTICATION_REQUIRED = 511intSTATUS_NETWORK_CONNECT_TIMEOUT_ERROR = 599intSTATUS_NETWORK_READ_TIMEOUT_ERROR = 598intSTATUS_NON_AUTHORITATIVE_INFORMATION = 203intSTATUS_NOT_ACCEPTABLE = 406intSTATUS_NOT_EXTENDED = 510intSTATUS_NOT_FOUND = 404intSTATUS_NOT_IMPLEMENTED = 501intSTATUS_NOT_MODIFIED = 304intSTATUS_NO_CONTENT = 204intSTATUS_NO_RESPONSE = 444intSTATUS_OK = 200intSTATUS_ORIGIN_DNS_ERROR = 530intSTATUS_ORIGIN_IS_UNREACHABLE = 523intSTATUS_PAGE_EXPIRED = 419intSTATUS_PARTIAL_CONTENT = 206intSTATUS_PAYLOAD_TOO_LARGE = 413intSTATUS_PAYMENT_REQUIRED = 402intSTATUS_PERMANENT_REDIRECT = 308intSTATUS_PRECONDITION_FAILED = 412intSTATUS_PRECONDITION_REQUIRED = 428intSTATUS_PROCESSING = 102intSTATUS_PROXY_AUTHENTICATION_REQUIRED = 407intSTATUS_RAILGUN_ERROR = 527intSTATUS_RANGE_NOT_SATISFIABLE = 416intSTATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431intSTATUS_REQUEST_HEADER_TOO_LARGE = 494intSTATUS_REQUEST_TIMEOUT = 408intSTATUS_RESERVED = 306intSTATUS_RESET_CONTENT = 205intSTATUS_RETRY_WITH = 449intSTATUS_SEE_OTHER = 303intSTATUS_SERVICE_UNAVAILABLE = 503intSTATUS_SSL_CERTIFICATE_ERROR = 495intSTATUS_SSL_CERTIFICATE_REQUIRED = 496intSTATUS_SSL_HANDSHAKE_FAILED = 525intSTATUS_SWITCHING_PROTOCOLS = 101intSTATUS_TEMPORARY_REDIRECT = 307intSTATUS_THIS_IS_FINE = 218intSTATUS_TIMEOUT_OCCURRED = 524intSTATUS_TOO_EARLY = 425intSTATUS_TOO_MANY_REQUESTS = 429intSTATUS_UNAUTHORIZED = 401intSTATUS_UNAVAILABLE_FOR_LEGAL_REASONS = 451intSTATUS_UNKNOWN_ERROR = 520intSTATUS_UNPROCESSABLE_ENTITY = 422intSTATUS_UNSUPPORTED_MEDIA_TYPE = 415intSTATUS_UPGRADE_REQUIRED = 426intSTATUS_URI_TOO_LONG = 414intSTATUS_USE_PROXY = 305intSTATUS_VARIANT_ALSO_NEGOTIATES = 506intSTATUS_VERSION_NOT_SUPPORTED = 505intSTATUS_WEB_SERVER_IS_DOWN = 521Http\Request
ClassSource on GitHubEncapsulates 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();\stdClassPhalcon\Di\AbstractInjectionAwarePhalcon\Http\Request- implementsPhalcon\Http\RequestInterface,Phalcon\Http\Message\RequestMethodInterface,Phalcon\Contracts\Http\AttributeRequest
Uses Phalcon\Contracts\Http\AttributeRequest · Phalcon\Contracts\Http\HttpTypes · Phalcon\Di\AbstractInjectionAware · Phalcon\Di\DiInterface · Phalcon\Events\ManagerInterface · Phalcon\Events\Traits\EventsAwareTrait · Phalcon\Filter\FilterInterface · Phalcon\Http\Message\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
publicmixedget(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
publicarraygetAcceptableContent()Gets an array with mime/types and their quality accepted by the
publicAttributeBaggetAttributes()Returns the request attributes bag. Attributes are arbitrary,
publicarray|nullgetBasicAuth()Gets auth info accepted by the browser/client from
publicstringgetBestAccept()Gets best mime/type accepted by the browser/client from
publicstringgetBestCharset()Gets best charset accepted by the browser/client from
publicstringgetBestLanguage()Gets the best language accepted by the browser/client from
publicstring|boolgetClientAddress(bool $trustForwardedHeader = false)Gets most possible client IP Address. This method searches in
publicarraygetClientCharsets()Gets a charsets array and their quality accepted by the browser/client
publicstring|nullgetContentType()Gets content type which request has been made
publicarraygetDigestAuth()Gets auth info accepted by the browser/client from
publicmixedgetFilteredData(string $methodKey,string $method,string|null $name = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false)Gets filtered data
publicmixedgetFilteredPatch(string|null $name = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false)Retrieves a patch value always sanitized with the preset filters
publicmixedgetFilteredPost(string|null $name = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false)Retrieves a post value always sanitized with the preset filters
publicmixedgetFilteredPut(string|null $name = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false)Retrieves a put value always sanitized with the preset filters
publicmixedgetFilteredQuery(string|null $name = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false)Retrieves a query/get value always sanitized with the preset filters
publicstringgetHTTPReferer()Gets web page that refers active request. ie: http://www.google.com
publicstringgetHeader(string $header)Gets HTTP header from request data
publicarraygetHeaders()Returns the available headers in the request
publicstringgetHttpHost()Gets host name used by the request.
publicboolgetHttpMethodParameterOverride()Return the HTTP method parameter override flag
public\stdClass|array|boolgetJsonRawBody(bool $associative = false)Gets decoded JSON HTTP raw request body
publicarraygetLanguages()Gets languages array and their quality accepted by the browser/client
publicstringgetMethod()Gets HTTP method which request has been made
publicmixedgetPatch(string|null $name = null,mixed $filters = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false)Gets a variable from put request
publicintgetPort()Gets information about the port on which the request is made.
publicmixedgetPost(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
publicstringgetPreferredIsoLocaleVariant()Gets the preferred ISO locale variant.
publicmixedgetPut(string|null $name = null,mixed $filters = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false)Gets a variable from the PUT request
publicmixedgetQuery(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.
publicstringgetRawBody()Gets HTTP raw request body
publicstringgetScheme()Gets HTTP schema (http/https)
publicstring|nullgetServer(string $name)Gets variable from $_SERVER superglobal
publicstringgetServerAddress()Gets active server address IP
publicstringgetServerName()Gets active server name
publicstringgetURI(bool $onlyPath = false)Gets HTTP URI which request has been made to
publicFileInterface[]getUploadedFiles(bool $onlySuccessful = false,bool $namedKeys = false)Gets attached files as Phalcon\Http\Request\File instances
publicstringgetUserAgent()Gets HTTP user agent used to make the request
publicboolhas(string $name)Checks whether $_REQUEST superglobal has certain index
publicboolhasFiles()Returns if the request has files or not
publicboolhasHeader(string $header)Checks whether headers has certain index
publicboolhasPatch(string $name)Checks whether the PATCH data has certain index
publicboolhasPost(string $name)Checks whether $_POST superglobal has certain index
publicboolhasPut(string $name)Checks whether the PUT data has certain index
publicboolhasQuery(string $name)Checks whether $_GET superglobal has certain index
publicboolhasServer(string $name)Checks whether $_SERVER superglobal has certain index
publicboolisAjax()Checks whether request has been made using ajax
publicboolisConnect()Checks whether HTTP method is CONNECT.
publicboolisDelete()Checks whether HTTP method is DELETE.
publicboolisGet()Checks whether HTTP method is GET.
publicboolisHead()Checks whether HTTP method is HEAD.
publicboolisJson()Checks whether request content type contains json data
publicboolisMethod(mixed $methods,bool $strict = false)Check if HTTP method match any of the passed methods
publicboolisOptions()Checks whether HTTP method is OPTIONS.
publicboolisPatch()Checks whether HTTP method is PATCH.
publicboolisPost()Checks whether HTTP method is POST.
publicboolisPurge()Checks whether HTTP method is PURGE (Squid and Varnish support).
publicboolisPut()Checks whether HTTP method is PUT.
publicboolisSecure()Checks whether request has been made using any secure layer
publicboolisSoap()Checks whether request has been made using SOAP
publicboolisStrictHostCheck()Checks if the Request::getHttpHost method will be use strict validation
publicboolisTrace()Checks whether HTTP method is TRACE.
publicboolisValidHttpMethod(string $method)Checks if a method is a valid HTTP method
publicintnumFiles(bool $onlySuccessful = false)Returns the number of files available
publicstaticsetHttpMethodParameterOverride(bool $override)Set the HTTP method parameter override flag
publicstaticsetParameterFilters(string $name,array $filters = [],array $scope = [])Sets automatic sanitizers/filters for a particular field and for
publicstaticsetStrictHostCheck(bool $flag = true)Sets if the Request::getHttpHost method must be use strict validation
publicstaticsetTrustedProxies(array $trustedProxies)Set a trusted proxy list for X-Forwarded-For header
publicstaticsetTrustedProxyHeader(string $trustedProxyHeader)This header takes priority when parsing HTTP headers
protectedstringgetBestQuality(array $qualityParts,string $name)Process a request header and return the one with best quality
protectedmixedgetHelper(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.
protectedarraygetQualityHeader(string $serverIndex,string $name)Process a request header and return an array of values with their
protectedinthasFileHelper(mixed $data,bool $onlySuccessful)Recursively counts file in an array of files
protectedboolisIpAddressInCIDR(string $ip,string $cidr)Check if an IP address exists in CIDR range
protectedarrayresolveAuthorizationHeaders()Resolve authorization headers.
protectedarraysmoothFiles(array $names,array $types,array $tmp_names,array $sizes,array $errors,string $prefix)Smooth out $_FILES to have plain array with all files uploaded
Properties
protectedAttributeBag|null$attributes = nullprotectedFilterInterface|null$filterService = nullprotectedbool$methodOverride = falseprotectedarray|null$postCache = nullprotectedarray$queryFilters = []protectedstring$rawBody = ""protectedbool$strictHostCheck = falseprotectedarray$trustedProxies = []protectedstring$trustedProxyHeader = ""Methods
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");@todo check the filters
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 ): string|bool;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: http://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.comgetHttpMethodParameterOverride()
public function getHttpMethodParameterOverride(): bool;Return the HTTP method parameter override flag
getJsonRawBody()
public function getJsonRawBody( bool $associative = false ): \stdClass|array|bool;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 the PUT request
// Returns value from PUT stream without sanitizing
$userEmail = $request->getPut("user_email");
// Returns value from PUT stream 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
): FileInterface[];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
@todo check the $methods type - refactor this !!
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.
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 $tmp_names,
array $sizes,
array $errors,
string $prefix
): array;Smooth out $_FILES to have plain array with all files uploaded
Http\RequestInterface
InterfaceSource on GitHubInterface for Phalcon\Http\Request
Phalcon\Http\RequestInterface
Uses Phalcon\Contracts\Http\HttpTypes · Phalcon\Http\Request\FileInterface · stdClass
Method Summary
publicmixedget(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
publicarraygetAcceptableContent()Return an array with mime/types and their quality accepted by the
publicarray|nullgetBasicAuth()Gets auth info accepted by the browser/client from
publicstringgetBestAccept()Return the best mime/type accepted by the browser/client from
publicstringgetBestCharset()Return the best charset accepted by the browser/client from
publicstringgetBestLanguage()Return the best language accepted by the browser/client from
publicstring|boolgetClientAddress(bool $trustForwardedHeader = false)Return the most possible client IPv4 Address. This method searches in
publicarraygetClientCharsets()Return a charset array and their quality accepted by the browser/client
publicstring|nullgetContentType()Return the content type which request has been made
publicarraygetDigestAuth()Return the auth info accepted by the browser/client from
publicstringgetHTTPReferer()Return the web page that refers active request. ie: https://phalcon.io
publicstringgetHeader(string $header)Return the HTTP header from request data
publicarraygetHeaders()Returns the available headers in the request
publicstringgetHttpHost()Return the host name used by the request.
publicarray|bool|stdClassgetJsonRawBody(bool $associative = false)Return the decoded JSON HTTP raw request body
publicarraygetLanguages()Return the languages array and their quality accepted by the
publicstringgetMethod()Return the HTTP method which request has been made
publicintgetPort()Return the information about the port on which the request is made
publicmixedgetPost(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.
publicmixedgetPut(string|null $name = null,mixed $filters = null,mixed $defaultValue = null,bool $notAllowEmpty = false,bool $noRecursive = false)Return a variable from put request
publicmixedgetQuery(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.
publicstringgetRawBody()Return the HTTP raw request body
publicstringgetScheme()Return the HTTP schema (http/https)
publicstring|nullgetServer(string $name)Return a variable from $_SERVER superglobal
publicstringgetServerAddress()Return the active server address IP
publicstringgetServerName()Return the active server name
publicstringgetURI(bool $onlyPath = false)Return the HTTP URI which request has been made to
publicFileInterface[]getUploadedFiles(bool $onlySuccessful = false,bool $namedKeys = false)Return the attached files as Phalcon\Http\Request\FileInterface
publicstringgetUserAgent()Return the HTTP user agent used to make the request
publicboolhas(string $name)Return whether the $_REQUEST superglobal has certain index
publicboolhasFiles()Return whether the request includes attached files
publicboolhasHeader(string $header)Return whether the headers have a certain index
publicboolhasPost(string $name)Return whether the $_POST superglobal has certain index
publicboolhasPut(string $name)Return whether the PUT data has certain index
publicboolhasQuery(string $name)Return whether the $_GET superglobal has certain index
publicboolhasServer(string $name)Return whether the $_SERVER superglobal has certain index
publicboolisAjax()Return whether the request has been made using ajax. Checks if
publicboolisConnect()Return whether the HTTP method is CONNECT. if
publicboolisDelete()Return whether the HTTP method is DELETE. if
publicboolisGet()Return whether the HTTP method is GET. if
publicboolisHead()Return whether the HTTP method is HEAD. if
publicboolisMethod(mixed $methods,bool $strict = false)Return if the current HTTP method matches any of the passed methods
publicboolisOptions()Return whether the HTTP method is OPTIONS. if
publicboolisPost()Return whether the HTTP method is POST. if
publicboolisPurge()Return whether the HTTP method is PURGE (Squid and Varnish support). if
publicboolisPut()Return whether the HTTP method is PUT. if
publicboolisSecure()Return whether the request has been made using any secure layer
publicboolisSoap()Return whether the request has been made using SOAP
publicboolisTrace()Return whether the HTTP method is TRACE.
publicintnumFiles(bool $onlySuccessful = false)Returns the number of files available
Methods
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");@todo check the filters here
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 ): string|bool;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;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;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.comgetJsonRawBody()
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");@todo check the filters
getPut()
public function getPut(
string|null $name = null,
mixed $filters = null,
mixed $defaultValue = null,
bool $notAllowEmpty = false,
bool $noRecursive = false
): mixed;Return a variable from put request
// Returns value from PUT stream without sanitizing
$userEmail = $request->getPut("user_email");
// Returns value from PUT stream with sanitizing
$userEmail = $request->getPut("user_email", "email");@todo check the filters
getQuery()
public function getQuery(
string|null $name = null,
mixed $filters = null,
mixed $defaultValue = null,
bool $notAllowEmpty = false,
bool $noRecursive = false
): mixed;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);@todo check the filters
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
): FileInterface[];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
AbstractSource on GitHubShared 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.
@implements ArrayAccess<int|string, mixed> @implements IteratorAggregate<int|string, mixed>
Phalcon\Http\Request\Bag\AbstractBag- implements\ArrayAccess,\Countable,\IteratorAggregate
Uses ArrayAccess · ArrayIterator · Countable · IteratorAggregate · Phalcon\Contracts\Http\HttpTypes · Phalcon\Http\Request\Exceptions\NullKeyException · Traversable
Method Summary
public__construct(array $items = [])AbstractBag constructor.
publicarrayall()Returns all the elements of the bag
publicvoidclear()Removes all the elements of the bag
publicintcount()Returns the number of elements in the bag
publicmixedget(mixed $key,mixed $defaultValue = null)Returns an element of the bag, or the default value if it is not set
publicarraygetArray(mixed $key,array $defaultValue = [])Returns an element of the bag as an array. The default value is
publicboolgetBool(mixed $key,bool $defaultValue = false)Returns an element of the bag cast to bool, or the default value if
publicfloatgetFloat(mixed $key,float $defaultValue = 0.0)Returns an element of the bag cast to float, or the default value if
publicintgetInt(mixed $key,int $defaultValue = 0)Returns an element of the bag cast to int, or the default value if
publicTraversablegetIterator()Returns the iterator of the bag
publicstringgetString(mixed $key,string $defaultValue = "")Returns an element of the bag cast to string, or the default value if
publicboolhas(mixed $key)Checks whether an element exists in the bag
publicbooloffsetExists(mixed $offset)Whether an offset exists
publicmixedoffsetGet(mixed $offset)Offset to retrieve
publicvoidoffsetSet(mixed $offset,mixed $value)Offset to set
publicvoidoffsetUnset(mixed $offset)Offset to unset
publicvoidremove(mixed $key)Removes an element from the bag
publicvoidset(mixed $key,mixed $value)Sets an element in the bag
protectedarraynormalizeItems(array $items)Normalizes the items at construction time. Identity in the base;
protectedstringnormalizeKey(mixed $key)Normalizes a key for lookups and writes. Identity in the base;
Properties
protectedarray$items = []Methods
__construct()
public function __construct( array $items = [] );AbstractBag constructor.
all()
public function all(): array;Returns all the elements of the bag
clear()
public function clear(): void;Removes all the elements of the bag
count()
public function count(): int;Returns the number of elements in the bag
get()
public function get(
mixed $key,
mixed $defaultValue = null
): mixed;Returns an element of the bag, or the default value if it is not set
getArray()
public function getArray(
mixed $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(
mixed $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(
mixed $key,
float $defaultValue = 0.0
): float;Returns an element of the bag cast to float, or the default value if it is not set
getInt()
public function getInt(
mixed $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(
mixed $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( mixed $key ): bool;Checks whether an element exists in the bag
offsetExists()
public function offsetExists( mixed $offset ): bool;Whether an offset exists
offsetGet()
public function offsetGet( mixed $offset ): mixed;Offset to retrieve
offsetSet()
public function offsetSet(
mixed $offset,
mixed $value
): void;Offset to set
offsetUnset()
public function offsetUnset( mixed $offset ): void;Offset to unset
remove()
public function remove( mixed $key ): void;Removes an element from the bag
set()
public function set(
mixed $key,
mixed $value
): void;Sets an element in the bag
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( mixed $key ): string;Normalizes a key for lookups and writes. Identity in the base; subclasses can override it to change key handling
Http\Request\Bag\AttributeBag
ClassSource on GitHubHolds 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.
Phalcon\Http\Request\Bag\AbstractBagPhalcon\Http\Request\Bag\AttributeBag
Http\Request\Exception
ClassSource on GitHubPhalcon\Http\Request\Exception
Exceptions thrown in Phalcon\Http\Request will use this class
Http\Request\Exceptions\FilterServiceUnavailable
ClassSource on GitHub\ExceptionPhalcon\Http\Request\ExceptionPhalcon\Http\Request\Exceptions\FilterServiceUnavailable
Uses Phalcon\Http\Request\Exception
Method Summary
Methods
__construct()
public function __construct();Http\Request\Exceptions\InvalidHost
ClassSource on GitHub\UnexpectedValueExceptionPhalcon\Http\Request\Exceptions\InvalidHost
Uses UnexpectedValueException
Method Summary
Methods
__construct()
public function __construct( string $host );Http\Request\Exceptions\InvalidHttpMethod
ClassSource on GitHub\ExceptionPhalcon\Http\Request\ExceptionPhalcon\Http\Request\Exceptions\InvalidHttpMethod
Uses Phalcon\Http\Request\Exception
Method Summary
Methods
__construct()
public function __construct( string $method );Http\Request\Exceptions\MissingFilters
ClassSource on GitHub\ExceptionPhalcon\Http\Request\ExceptionPhalcon\Http\Request\Exceptions\MissingFilters
Uses Phalcon\Http\Request\Exception
Method Summary
Methods
__construct()
public function __construct( string $name );Http\Request\Exceptions\NullKeyException
ClassSource on GitHubThrown 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.
\ExceptionPhalcon\Http\Request\ExceptionPhalcon\Http\Request\Exceptions\NullKeyException
Uses Phalcon\Http\Request\Exception
Method Summary
Methods
__construct()
public function __construct();Http\Request\Exceptions\SanitizerNotFound
ClassSource on GitHub\ExceptionPhalcon\Http\Request\ExceptionPhalcon\Http\Request\Exceptions\SanitizerNotFound
Uses Phalcon\Http\Request\Exception
Method Summary
Methods
__construct()
public function __construct( string $sanitizer );Http\Request\File
ClassSource on GitHubPhalcon\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";
}
}
}
}Phalcon\Http\Request\File- implementsPhalcon\Http\Request\FileInterface
Uses Phalcon\Contracts\Http\HttpTypes · Phalcon\Traits\Support\Helper\Arr\GetTrait
Method Summary
public__construct(array $file,string $key = "")Constructor
publicintgetError()publicstringgetExtension()publicstringgetKey()publicstringgetName()Returns the real name of the uploaded file
publicstringgetRealType()Gets the real mime type of the upload file using finfo
publicintgetSize()Returns the file size of the uploaded file
publicstringgetTempName()Returns the temporary name of the uploaded file
publicstringgetType()Returns the mime type reported by the browser
publicboolisUploadedFile()Checks whether the file has been uploaded via Post.
publicboolmoveTo(string $destination)Moves the temporary file to a destination within the application
Properties
protectedint$error = 0protectedstring$extension = ""protectedstring$key = ""protectedstring$name = ""protectedstring$realTypeprotectedint$size = 0protectedstring$tmpName = ""protectedstring$type = ""Methods
__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
InterfaceSource on GitHubInterface for Phalcon\Http\Request\File
Phalcon\Http\Request\FileInterface
Method Summary
publicintgetError()Returns the error if any
publicstringgetName()Returns the real name of the uploaded file
publicstringgetRealType()Gets the real mime type of the upload file using finfo
publicintgetSize()Returns the file size of the uploaded file
publicstringgetTempName()Returns the temporal name of the uploaded file
publicstringgetType()Returns the mime type reported by the browser
publicboolmoveTo(string $destination)Move the temporary file to a destination
Methods
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
ClassSource on GitHubPart 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();Phalcon\Http\Response- implementsPhalcon\Http\ResponseInterface,Phalcon\Di\InjectionAwareInterface,Phalcon\Events\EventsAwareInterface,Phalcon\Http\Message\ResponseStatusCodeInterface
Uses DateTime · DateTimeZone · Phalcon\Di\Di · Phalcon\Di\DiInterface · Phalcon\Di\InjectionAwareInterface · Phalcon\Events\EventsAwareInterface · Phalcon\Events\ManagerInterface · Phalcon\Events\Traits\EventsAwareTrait · 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,mixed $code = null,mixed $status = null)Constructor
publicResponseInterfaceappendContent(mixed $content)Appends a string to the HTTP response body
publicstringgetContent()Gets the HTTP response body
publicCookiesInterfacegetCookies()Returns cookies set by the user
publicDiInterfacegetDI()Returns the internal dependency injector
publicHeadersInterfacegetHeaders()Returns headers set by the user
publicstring|nullgetReasonPhrase()Returns the reason phrase
publicint|nullgetStatusCode()Returns the status code
publicboolhasHeader(string $name)Checks if a header exists
publicboolisSent()Check if the response is already sent
publicResponseInterfaceredirect(mixed $location = null,bool $externalRedirect = false,int $statusCode = 302)Redirect by HTTP to another action or URL
publicResponseInterfaceremoveHeader(string $name)Remove a header in the response
publicResponseInterfaceresetHeaders()Resets all the established headers
publicResponseInterfacesend()Prints out HTTP response to the client
publicResponseInterfacesendCookies()Sends cookies to the client
publicResponseInterface|boolsendHeaders()Sends headers to the client
publicResponseInterfacesetCache(int $minutes)Sets Cache headers to use HTTP cache
publicResponseInterfacesetContent(string $content)Sets HTTP response body
publicResponseInterfacesetContentLength(int $contentLength)Sets the response content-length
publicResponseInterfacesetContentType(string $contentType,string|null $charset = null)Sets the response content-type mime, optionally the charset
publicResponseInterfacesetCookies(CookiesInterface $cookies)Sets a cookies bag for the response externally
publicvoidsetDI(DiInterface $container)Sets the dependency injector
publicResponseInterfacesetEtag(string $etag)Set a custom ETag
publicResponseInterfacesetExpires(DateTime $datetime)Sets an Expires header in the response that allows to use the HTTP cache
publicResponseInterfacesetFileToSend(string $filePath,mixed $attachmentName = null,bool $attachment = true)Sets an attached file to be sent at the end of the request
publicResponseInterfacesetHeader(string $name,mixed $value)Overwrites a header in the response
publicResponseInterfacesetHeaders(HeadersInterface $headers)Sets a headers bag for the response externally
publicResponseInterfacesetJsonContent(mixed $content,int $jsonOptions = 0,int $depth = 512)Sets HTTP response body. The parameter is automatically converted to JSON
publicResponseInterfacesetLastModified(DateTime $datetime)Sets Last-Modified header
publicResponseInterfacesetNotModified()Sends a Not-Modified response
publicResponseInterfacesetRawHeader(string $header)Send a raw header to the response
publicResponseInterfacesetStatusCode(int $code,string|null $message = null)Sets the HTTP response code
Properties
protectedDiInterface|null$container = nullprotectedstring|null$content = nullprotectedCookiesInterface|null$cookies = nullprotectedEncode$encodeprotectedstring|null$file = nullprotectedHeaders$headersprotectedbool$sent = falseMethods
__construct()
public function __construct(
string|null $content = null,
mixed $code = null,
mixed $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(
mixed $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(): ResponseInterface|bool;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
setDI()
public function setDI( DiInterface $container ): void;Sets the dependency injector
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,
mixed $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
InterfaceSource on GitHubPhalcon\Http\Response
Interface for Phalcon\Http\Response
Phalcon\Http\ResponseInterface
Uses DateTime · Phalcon\Http\Response\HeadersInterface
Method Summary
publicResponseInterfaceappendContent(string $content)Appends a string to the HTTP response body
publicstringgetContent()Gets the HTTP response body
publicHeadersInterfacegetHeaders()Returns headers set by the user
publicint|nullgetStatusCode()Returns the status code
publicboolhasHeader(string $name)Checks if a header exists
publicboolisSent()Checks if the response was already sent
publicResponseInterfaceredirect(string|null $location = null,bool $externalRedirect = false,int $statusCode = 302)Redirect by HTTP to another action or URL
publicResponseInterfaceresetHeaders()Resets all the established headers
publicResponseInterfacesend()Prints out HTTP response to the client
publicResponseInterfacesendCookies()Sends cookies to the client
publicbool|ResponseInterfacesendHeaders()Sends headers to the client
publicResponseInterfacesetContent(string $content)Sets HTTP response body
publicResponseInterfacesetContentLength(int $contentLength)Sets the response content-length
publicResponseInterfacesetContentType(string $contentType,string|null $charset = null)Sets the response content-type mime, optionally the charset
publicResponseInterfacesetExpires(DateTime $datetime)Sets output expire time header
publicResponseInterfacesetFileToSend(string $filePath,string|null $attachmentName = null)Sets an attached file to be sent at the end of the request
publicResponseInterfacesetHeader(string $name,string $value)Overwrites a header in the response
publicResponseInterfacesetJsonContent(mixed $content)Sets HTTP response body. The parameter is automatically converted to JSON
publicResponseInterfacesetNotModified()Sends a Not-Modified response
publicResponseInterfacesetRawHeader(string $header)Send a raw header to the response
publicResponseInterfacesetStatusCode(int $code,string|null $message = null)Sets the HTTP response code
Methods
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
@todo check the null
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
@todo check the null
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",
]
);@todo check the parameter type
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
@todo change $message to only string
Http\Response\Cookies
ClassSource on GitHubThis 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;
}
);\stdClassPhalcon\Di\AbstractInjectionAwarePhalcon\Http\Response\Cookies- implementsPhalcon\Http\Response\CookiesInterface
Uses Phalcon\Contracts\Http\HttpTypes · Phalcon\Di\AbstractInjectionAware · Phalcon\Di\DiInterface · Phalcon\Http\Cookie · Phalcon\Http\Cookie\CookieInterface · Phalcon\Http\Cookie\Exception · Phalcon\Http\Response\Exceptions\ResponseServiceUnavailable · Phalcon\Http\Traits\EncryptionAwareTrait
Method Summary
public__construct(bool $useEncryption = true,string|null $signKey = null)Constructor
publicbooldelete(string $name)Deletes a cookie by its name
publicCookieInterfaceget(string $name)Gets a cookie from the bag
publicarraygetCookies()Gets all cookies from the bag
publicboolhas(string $name)Check if a cookie is defined in the bag or exists in the _COOKIE
publicboolisSent()Returns if the headers have already been sent
publicCookiesInterfacereset()Reset set cookies
publicboolsend()Sends the cookies to the client
publicCookiesInterfaceset(string $name,mixed $value = null,int $expire = 0,string $path = "/",bool $secure = false,string $domain = "",bool $httpOnly = false,array $options = [])Sets a cookie to be sent at the end of the request.
publicCookiesInterfacesetSignKey(string|null $signKey = null)Sets the cookie’s sign key.
publicCookiesInterfaceuseEncryption(bool $useEncryption)Set if cookies in the bag must be automatically encrypted/decrypted
Properties
protectedarray$cookies = []protectedbool$isRegistered = falseprotectedbool$isSent = falseprotectedstring|null$signKey = nullThe cookie’s sign key.
Methods
__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.
@see \Phalcon\Encryption\Security\Random
useEncryption()
public function useEncryption( bool $useEncryption ): CookiesInterface;Set if cookies in the bag must be automatically encrypted/decrypted
Http\Response\CookiesInterface
InterfaceSource on GitHubInterface for Phalcon\Http\Response\Cookies
Phalcon\Http\Response\CookiesInterface
Uses Phalcon\Contracts\Http\HttpTypes · Phalcon\Http\Cookie\CookieInterface
Method Summary
publicbooldelete(string $name)Deletes a cookie by its name
publicCookieInterfaceget(string $name)Gets a cookie from the bag
publicboolhas(string $name)Check if a cookie is defined in the bag or exists in the _COOKIE superglobal
publicboolisUsingEncryption()Returns if the bag is automatically encrypting/decrypting cookies
publicCookiesInterfacereset()Reset set cookies
publicboolsend()Sends the cookies to the client
publicCookiesInterfaceset(string $name,mixed $value = null,int $expire = 0,string $path = "/",bool $secure = false,string $domain = "",bool $httpOnly = false,array $options = [])Sets a cookie to be sent at the end of the request
publicCookiesInterfaceuseEncryption(bool $useEncryption)Set if cookies in the bag must be automatically encrypted/decrypted
Methods
delete()
public function delete( string $name ): bool;Deletes a cookie by its name This method does not removes 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
ClassSource on GitHubPhalcon\Http\Response\Exception
Exceptions thrown in Phalcon\Http\Response will use this class.
Http\Response\Exceptions\NonStandardStatusCodeRequiresMessage
ClassSource on GitHub\ExceptionPhalcon\Http\Response\ExceptionPhalcon\Http\Response\Exceptions\NonStandardStatusCodeRequiresMessage
Uses Phalcon\Http\Response\Exception
Method Summary
Methods
__construct()
public function __construct();Http\Response\Exceptions\ResponseAlreadySent
ClassSource on GitHub\ExceptionPhalcon\Http\Response\ExceptionPhalcon\Http\Response\Exceptions\ResponseAlreadySent
Uses Phalcon\Http\Response\Exception
Method Summary
Methods
__construct()
public function __construct();Http\Response\Exceptions\ResponseServiceUnavailable
ClassSource on GitHub\ExceptionPhalcon\Http\Response\ExceptionPhalcon\Http\Response\Exceptions\ResponseServiceUnavailable
Uses Phalcon\Http\Response\Exception
Method Summary
Methods
__construct()
public function __construct();Http\Response\Exceptions\UrlServiceUnavailable
ClassSource on GitHub\ExceptionPhalcon\Http\Response\ExceptionPhalcon\Http\Response\Exceptions\UrlServiceUnavailable
Uses Phalcon\Http\Response\Exception
Method Summary
Methods
__construct()
public function __construct();Http\Response\Headers
ClassSource on GitHubThis class is a bag to manage the response headers
@implements IteratorAggregate<string, string|null>
Phalcon\Http\Response\Headers- implementsPhalcon\Http\Response\HeadersInterface,\IteratorAggregate
Uses IteratorAggregate · Phalcon\Contracts\Http\HttpTypes · Traversable
Method Summary
publicstring|bool|nullget(string $name)Gets a header value from the internal bag
publicTraversablegetIterator()publicboolhas(string $name)Checks if a header exists
publicboolisSent()Returns if the headers have already been sent
publicHeadersInterfaceremove(string $header)Removes a header by its name
publicvoidreset()Reset set headers
publicboolsend()Sends the headers to the client
publicHeadersInterfaceset(string $name,string $value)Sets a header to be sent at the end of the request
publicHeadersInterfacesetRaw(string $header)Sets a raw header to be sent at the end of the request
publicarraytoArray()Returns the current headers as an array
Properties
protectedarray$headers = []protectedbool$isSent = falseMethods
get()
public function get( string $name ): string|bool|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 $header ): 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
InterfaceSource on GitHubInterface for Phalcon\Http\Response\Headers compatible bags
Phalcon\Http\Response\HeadersInterface
Method Summary
publicbool|string|nullget(string $name)Gets a header value from the internal bag
publicboolhas(string $name)Checks if a header exists
publicvoidreset()Reset set headers
publicboolsend()Sends the headers to the client
publicHeadersInterfaceset(string $name,string $value)Sets a header to be sent at the end of the request
publicHeadersInterfacesetRaw(string $header)Sets a raw header to be sent at the end of the request
Methods
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
TraitSource on GitHubProvides 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
protectedbool$useEncryption = falseMethods
isUsingEncryption()
public function isUsingEncryption(): bool;Check if implicit encryption is being used
Http\Traits\StatusPhrasesTrait
TraitSource on GitHubStatus Phrases trait
Phalcon\Http\Traits\StatusPhrasesTrait
Uses Phalcon\Http\Message\ResponseStatusCodeInterface
Used by Phalcon\Http\Response
Method Summary
Methods
getPhrases()
protected function getPhrases(): array;Returns the list of status codes available