{"id":18750693,"url":"https://github.com/webiny/http","last_synced_at":"2025-10-05T05:52:10.017Z","repository":{"id":20227143,"uuid":"23498983","full_name":"webiny/Http","owner":"webiny","description":"[READ-ONLY]  Http is a PHP component provides an objective approach to working with HTTP request, response and cache control.  (master at Webiny/Framework)","archived":false,"fork":false,"pushed_at":"2017-11-26T21:24:46.000Z","size":54,"stargazers_count":1,"open_issues_count":0,"forks_count":1,"subscribers_count":10,"default_branch":"master","last_synced_at":"2024-12-28T22:54:04.775Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"http://www.webiny.com/","language":"PHP","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/webiny.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2014-08-30T19:22:04.000Z","updated_at":"2023-05-21T17:38:28.000Z","dependencies_parsed_at":"2022-07-27T01:02:20.159Z","dependency_job_id":null,"html_url":"https://github.com/webiny/Http","commit_stats":null,"previous_names":[],"tags_count":15,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webiny%2FHttp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webiny%2FHttp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webiny%2FHttp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webiny%2FHttp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/webiny","download_url":"https://codeload.github.com/webiny/Http/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":239636196,"owners_count":19672298,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-07T17:12:49.799Z","updated_at":"2025-10-05T05:52:09.921Z","avatar_url":"https://github.com/webiny.png","language":"PHP","readme":"Http Component\n==============\n\nThe `Http` component consists of a `Request`, `Response`, `Cookie` and `Session` class.\n\nInstall the component\n---------------------\nThe best way to install the component is using Composer.\n\n```bash\ncomposer require webiny/http\n```\nFor additional versions of the package, visit the [Packagist page](https://packagist.org/packages/webiny/http).\n\n## Usage\n\nThe preferred way of accessing those classes is by using the `HttpTrait`.\n\n```php\n    class MyClass{\n        use \\Webiny\\Component\\Http\\HttpTrait;\n\n        function myFunction(){\n            // access `Request` instance\n            $this-\u003ehttpRequest();\n\n            // access `Cookie` instance\n            $this-\u003ehttpCookie();\n\n            // access `Session` instance\n            $this-\u003ehttpSession();\n\n            // create new `Response` instance\n            $this-\u003ehttpResponse('output content');\n             \n            // redirect\n            $this-\u003ehttpRedirect('http://youtube.com/');\n        }\n    }\n```\n\nTo register the config with the component, just call `Http::setConfig($pathToYamlConfig)`.\n\n# `Request` class\n\nThe `Request` class provides different helper methods like:\n- **getCurrentUrl** - returns current url\n- **getClientIp** - returns the IP address of current client\n- **isRequestSecured** - checks if the request is behind a 'https' protocol\n\nAnd a lot of other methods.\n**NOTE:** All of the functions check for forwarded response headers and validate them against\nthe defined list of trusted proxies.\n\nOther than just providing helper functions, the `Request` class gives you also objective wrappers for working with\nglobal variables like `$_SERVER`, `$_GET`, `$_POST` and `$_FILES`.\n\n## `Server`\n\nThe `Server` class is a wrapper for all of (documented) $_SERVER properties, based on the list on official php.net documentation.\nhttp://php.net/manual/en/reserved.variables.server.php\n\nHere is an example usage:\n```php\nclass MyClass{\n        use \\Webiny\\Component\\Http\\HttpTrait;\n\n        function myFunction(){\n           // get request method\n            $this-\u003ehttpRequest()-\u003eserver()-\u003erequestMethod(); // \"GET\"\n        }\n    }\n```\n\n**NOTE:** `Server` methods **do not** check forwarded response headers from reverse proxies. They are just an objective\nwrapper for $_SERVER properties.\nUse the methods from the `Request` class to get client ip, host name, and similar properties that validate against\ntrusted proxies.\n\n## `$_GET` and `$_POST`\n\nTo access the `$_GET` properties use the `query` method, and to access the `$_POST` use the `post` method.\nBoth methods take two params. First param is the key of the property, and the second is the default value that will be\nreturned in case if the key does not exist.\n\nHere is an example usage:\n```php\nclass MyClass{\n        use \\Webiny\\Component\\Http\\HttpTrait;\n\n        function myFunction(){\n            // get 'name' param from current query string\n            $this-\u003ehttpRequest()-\u003equery('name');\n\n            // get 'color' param from $_POST, and if color is not defined, return 'blue'\n            $this-\u003ehttpRequest()-\u003epost('color', 'blue');\n        }\n    }\n```\n\n## `Payload`\n\nTo access the `Payload` property, use the `payload` method. `Payload` automatically reads `php://input` and `json_decode`s\nthe output.\n\nTo access payload values:\n```php\nclass MyClass{\n        use \\Webiny\\Component\\Http\\HttpTrait;\n\n        function myFunction(){\n            // get 'name' from payload\n            $this-\u003ehttpRequest()-\u003epayload('name');\n        }\n    }\n```\n\n## `$_FILES`\n\nThe `$_FILES` wrapper provides a much better way of handling uploaded files. The process consists of two steps. In the\nfirst step, you get the file using the `files` method on the `Request` class. After that you can move the file to desired\ndestination.\n\n```php\nclass MyClass{\n        use \\Webiny\\Component\\Http\\HttpTrait;\n\n        function myFunction(){\n            // get the uploaded file\n            $file = $this-\u003ehttpRequest()-\u003efiles('avatar');\n\n            // move it to desired destination\n            $file-\u003estore('/var/tmp');\n        }\n    }\n```\n\n# `Session` class\n\nWebiny framework provides you with two built-in session storage handlers, the native handler and the cache handler.\nNative handler uses the built-in PHP session handler, while cache handler uses the provided cache driver.\nUsing the cache handler you can easily share your sessions across multiple servers and boost performance. Current supported\ncache drivers are all supported drivers by the `Cache` component.\n\n## Session cache handler configuration\n\nThe default defined storage handler is the native handler. If you want to use the cache handler you must first setup a\ncache driver (read the `Cache` component readme file) and then just link the cache driver to the session handler like this:\n\n```yaml\n    Http:\n        Session:\n            Storage:\n                Driver: '\\Webiny\\Component\\Http\\Session\\Storage\\CacheStorage'\n                Params:\n                    Cache: 'TestCache'\n                Prefix: 'wfs_'\n                ExpireTime: 86400\n```\n\nThere are two most important properties you have to change, the `Driver` and `Params.Cache`. The `Driver` property\nmust point to `\\Webiny\\Component\\Http\\Session\\Storage\\CacheStorage` and `Params.Cache` must have the name\nof a registered `Cache` service.\nNo other changes are required in your code, you can work with sessions using the `Session` class.\n\n## Custom session storage handler\n\nYou can implement your own session storage handler by creating a class that implements\n`\\Webiny\\Component\\Http\\Session\\SessionStorageInterface`. After you have created such a class, just point the\n`Driver` param to your class and, optionally, pass the requested constructor params using the `Params` config attribute.\n\n## Working with sessions\n\nTo work with sessions is rather easy, just access the current session handler which then provides you with the necessary\nsession methods like `get`, `save` and `getSessionId`.\n\nHere is an example:\n\n```php\nclass MyClass{\n        use \\Webiny\\Component\\Http\\HttpTrait;\n\n        function myFunction(){\n            // save into session\n            $this-\u003ehttpSession()-\u003esave('my_key', 'some value');\n\n            // read from session\n            $this-\u003ehttpSession()-\u003eget('my_key');\n        }\n    }\n```\n\n# `Cookie` class\n\nWorking with cookies is similar to working with sessions, you have a cookie storage handler that gives you the\nnecessary methods for storing and accessing cookie values. By default there is only a native built-in storage handler.\n\n## Cookie configuration\n\nThe cookie configuration consists of defining the default storage driver and some optional parameters like `Prefix`,\n`HttpOnly` and `ExpireTime`.\n\n```yaml\n    Http:\n        Cookie:\n            Storage:\n                Driver: '\\Webiny\\Component\\Http\\Cookie\\Storage\\NativeStorage'\n            Prefix: 'wfc_'\n            HttpOnly: 'true'\n            ExpireTime: 86400\n```\n\n## Custom cookie storage handler\n\nTo implement a custom cookie storage handler, you first need to create a storage handler class which implements the\n`\\Webiny\\Component\\Http\\Cookie\\CookieStorageHandler` interface. After you have successfully created your class,\nyou now have to change the `Storage.Driver` parameter in your cookie configuration to point to your class.\n\n## Working with cookies\n\nIn order to read and store cookies you have to get the instance of current cookie storage driver which provides you with\nthe necessary methods. The `Cookie` class provides you with that access:\n\n```php\nclass MyClass{\n        use \\Webiny\\Component\\Http\\HttpTrait;\n\n        function myFunction(){\n            // save cookie\n            $this-\u003ehttpCookie()-\u003esave('my_cookie', 'some value');\n\n            // read cookie\n            $this-\u003ehttpCookie()-\u003eget('my_key');\n        }\n    }\n```\n\n# `Response` class\n\nThe `Response` class provides methods for building an sending an output back to the browser.\nThe class itself doesn't require any configuration.\n\nTo create a `Response` instance, you can use the `HttpTrait`, the class constructor or `Response::create` static method.\n\n```php\n\n    // using the trait\n    class MyClass{\n        use \\Webiny\\Component\\Http\\HttpTrait;\n\n        function myFunction(){\n            // create and sent the output\n            $this-\u003ehttpResponse('Hello World!')-\u003esend();\n        }\n    }\n\n    // using constructor\n    $response = new Response('Hello World!');\n    $response-\u003esend();\n\n    // using static method\n    $response = Response::create('Hello World!');\n    $response-\u003esend();\n```\n\n## Methods\n\nThe `Response` class provides you with several helpful methods:\n- `setContent`: sets the output content\n- `setStatusCode`: sets the HTTP status code\n- `setContentType`: sets the content type header (default is: \"text/html\")\n- `setContentType`: sets the content char set (default is: \"UTF-8\")\n- `setHeader`: sets or adds a header to the response\n\n## Cache control\n\nA cache control class is provided to control the cache control headers on the response object.\nTo access the cache control options, use the `cacheControl` method on the `Response` object.\n\n```php\n    $response = new Response('Hello World!');\n    $cacheControl = $response-\u003ecacheControl();\n```\n\n`CacheControl` by default calls the `setAsDontCache` method which sets the cache control headers so that the response\nis not cached by the browser. To overwrite that, you can either provide an array with your own cache control header information or you can just call the `setAsCache` method which sets the response cache headers so the output can be cached by the browser.\n\n## `JsonResponse`\n\nThis class extends the `Response` class by setting the default content type to \"application/json\". The class can be accessed by a constructor or by a static short-hand method:\n\n```php\n    // using constructor\n    $jsonResponse = new Response\\JsonResponse($someArrayOrObject);\n    $jsonResponse-\u003esend(); // send output to browser\n\n    // short-hand\n    Response\\JsonResponse::sendJson($someArrayOrObject)); // output is automatically sent\n```\n\nResources\n---------\n\nTo run unit tests, you need to use the following command:\n\n    $ cd path/to/Webiny/Component/Http/\n    $ composer.phar install\n    $ phpunit","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwebiny%2Fhttp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwebiny%2Fhttp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwebiny%2Fhttp/lists"}