├── .github └── workflows │ └── main.yaml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── composer.json ├── phpcs.xml ├── phpunit.xml └── src └── Geolocation.php /.github/workflows/main.yaml: -------------------------------------------------------------------------------- 1 | name: "testing" 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | qa: 11 | name: Quality assurance 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - name: Checkout 16 | uses: actions/checkout@v4 17 | 18 | - name: Validate composer.json and composer.lock 19 | run: composer validate 20 | 21 | - name: Cache Composer packages 22 | id: composer-cache 23 | uses: actions/cache@v4 24 | with: 25 | path: vendor 26 | key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }} 27 | restore-keys: | 28 | ${{ runner.os }}-php- 29 | 30 | - name: Install dependencies 31 | if: steps.composer-cache.outputs.cache-hit != 'true' 32 | run: composer install --prefer-dist --no-progress 33 | 34 | - name: Coding Standard 35 | run: composer run-script cs 36 | 37 | tests: 38 | name: Tests 39 | runs-on: ubuntu-latest 40 | 41 | strategy: 42 | matrix: 43 | php: 44 | - 7.2 45 | - 7.3 46 | - 7.4 47 | - 8.0 48 | - 8.1 49 | - 8.2 50 | - 8.3 51 | - 8.4 52 | 53 | steps: 54 | - name: Checkout 55 | uses: actions/checkout@v4 56 | 57 | - name: Install PHP 58 | uses: shivammathur/setup-php@v2 59 | with: 60 | php-version: ${{ matrix.php }} 61 | 62 | - name: Cache PHP dependencies 63 | uses: actions/cache@v4 64 | with: 65 | path: vendor 66 | key: ${{ runner.os }}-php-${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} 67 | restore-keys: ${{ runner.os }}-php-${{ matrix.php }}-composer- 68 | 69 | - name: Install dependencies 70 | run: composer install --prefer-dist --no-progress 71 | 72 | - name: Tests 73 | run: composer test 74 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](http://keepachangelog.com/) 6 | and this project adheres to [Semantic Versioning](http://semver.org/). 7 | 8 | ## [3.1.0] - 2025-03-21 9 | ### Added 10 | - Support for PHP 8.4 11 | 12 | ## [3.0.0] - 2020-12-04 13 | ### Added 14 | - Support for PHP 8 15 | 16 | ### Removed 17 | - Support for PHP 7.0 and 7.1 18 | 19 | ### Fixed 20 | - Use `phpstan` as a dev dependency to detect bugs 21 | 22 | ## [2.0.0] - 2018-08-04 23 | ### Added 24 | - PSR-17 support 25 | 26 | ### Changed 27 | - The argument to pass the `Geocoder\Provider\Provider` in the constructor is mandatory. Removed the FreeGeoIp default provider because it requires credentials. 28 | 29 | ## [1.0.0] - 2018-01-27 30 | ### Added 31 | - Improved testing and added code coverage reporting 32 | - Added tests for PHP 7.2 33 | 34 | ### Changed 35 | - Upgraded to the final version of PSR-15 `psr/http-server-middleware` 36 | 37 | ### Fixed 38 | - Updated license year 39 | 40 | ## [0.5.0] - 2017-11-13 41 | ### Changed 42 | - Replaced `http-interop/http-middleware` with `http-interop/http-server-middleware`. 43 | 44 | ### Removed 45 | - Removed support for PHP 5.x. 46 | 47 | ## [0.4.0] - 2017-09-21 48 | ### Changed 49 | - Append `.dist` suffix to phpcs.xml and phpunit.xml files 50 | - Changed the configuration of phpcs and php_cs 51 | - Upgraded phpunit to the latest version and improved its config file 52 | - Updated to `http-interop/http-middleware#0.5` 53 | 54 | ## [0.3.0] - 2016-12-26 55 | ### Changed 56 | - Updated tests 57 | - Updated to `http-interop/http-middleware#0.4` 58 | - Updated `friendsofphp/php-cs-fixer#2.0` 59 | 60 | ## [0.2.0] - 2016-11-27 61 | ### Changed 62 | - Updated to `http-interop/http-middleware#0.3` 63 | 64 | ## 0.1.0 - 2016-10-10 65 | First version 66 | 67 | [3.1.0]: https://github.com/middlewares/geolocation/compare/v3.0.0...v3.1.0 68 | [3.0.0]: https://github.com/middlewares/geolocation/compare/v2.0.0...v3.0.0 69 | [2.0.0]: https://github.com/middlewares/geolocation/compare/v1.0.0...v2.0.0 70 | [1.0.0]: https://github.com/middlewares/geolocation/compare/v0.5.0...v1.0.0 71 | [0.5.0]: https://github.com/middlewares/geolocation/compare/v0.4.0...v0.5.0 72 | [0.4.0]: https://github.com/middlewares/geolocation/compare/v0.3.0...v0.4.0 73 | [0.3.0]: https://github.com/middlewares/geolocation/compare/v0.2.0...v0.3.0 74 | [0.2.0]: https://github.com/middlewares/geolocation/compare/v0.1.0...v0.2.0 75 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guide 2 | 3 | This project adheres to [The Code Manifesto](http://codemanifesto.com) as its guidelines for contributor interactions. 4 | 5 | ## The Code Manifesto 6 | 7 | We want to work in an ecosystem that empowers developers to reach their potential--one that encourages growth and effective collaboration. A space that is safe for all. 8 | 9 | A space such as this benefits everyone that participates in it. It encourages new developers to enter our field. It is through discussion and collaboration that we grow, and through growth that we improve. 10 | 11 | In the effort to create such a place, we hold to these values: 12 | 13 | 1. **Discrimination limits us.** This includes discrimination on the basis of race, gender, sexual orientation, gender identity, age, nationality, technology and any other arbitrary exclusion of a group of people. 14 | 2. **Boundaries honor us.** Your comfort levels are not everyone’s comfort levels. Remember that, and if brought to your attention, heed it. 15 | 3. **We are our biggest assets.** None of us were born masters of our trade. Each of us has been helped along the way. Return that favor, when and where you can. 16 | 4. **We are resources for the future.** As an extension of #3, share what you know. Make yourself a resource to help those that come after you. 17 | 5. **Respect defines us.** Treat others as you wish to be treated. Make your discussions, criticisms and debates from a position of respectfulness. Ask yourself, is it true? Is it necessary? Is it constructive? Anything less is unacceptable. 18 | 6. **Reactions require grace.** Angry responses are valid, but abusive language and vindictive actions are toxic. When something happens that offends you, handle it assertively, but be respectful. Escalate reasonably, and try to allow the offender an opportunity to explain themselves, and possibly correct the issue. 19 | 7. **Opinions are just that: opinions.** Each and every one of us, due to our background and upbringing, have varying opinions. That is perfectly acceptable. Remember this: if you respect your own opinions, you should respect the opinions of others. 20 | 8. **To err is human.** You might not intend it, but mistakes do happen and contribute to build experience. Tolerate honest mistakes, and don't hesitate to apologize if you make one yourself. 21 | 22 | ## How to contribute 23 | 24 | This is a collaborative effort. We welcome all contributions submitted as pull requests. 25 | 26 | (Contributions on wording & style are also welcome.) 27 | 28 | ### Bugs 29 | 30 | A bug is a demonstrable problem that is caused by the code in the repository. Good bug reports are extremely helpful – thank you! 31 | 32 | Please try to be as detailed as possible in your report. Include specific information about the environment – version of PHP, etc, and steps required to reproduce the issue. 33 | 34 | ### Pull Requests 35 | 36 | Good pull requests – patches, improvements, new features – are a fantastic help. Before create a pull request, please follow these instructions: 37 | 38 | * The code must follow the [PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md). Run `composer cs-fix` to fix your code before commit. 39 | * Write tests 40 | * Document any change in `README.md` and `CHANGELOG.md` 41 | * One pull request per feature. If you want to do more than one thing, send multiple pull request 42 | 43 | ### Runing tests 44 | 45 | ```sh 46 | composer test 47 | ``` 48 | 49 | To get code coverage information execute the following comand: 50 | 51 | ```sh 52 | composer coverage 53 | ``` 54 | 55 | Then, open the `./coverage/index.html` file in your browser. 56 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018-2025 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # middlewares/geolocation 2 | 3 | [![Latest Version on Packagist][ico-version]][link-packagist] 4 | [![Software License][ico-license]](LICENSE) 5 | ![Testing][ico-ga] 6 | [![Total Downloads][ico-downloads]][link-downloads] 7 | [![SensioLabs Insight][ico-sensiolabs]][link-sensiolabs] 8 | 9 | Middleware to geolocate the client using the ip address and [Geocoder](https://github.com/geocoder-php/Geocoder) and save the result as a request attribute. 10 | 11 | ## Requirements 12 | 13 | * PHP >= 7.0 14 | * A [PSR-7 http library](https://github.com/middlewares/awesome-psr15-middlewares#psr-7-implementations) 15 | * A [PSR-15 middleware dispatcher](https://github.com/middlewares/awesome-psr15-middlewares#dispatcher) 16 | * A [PHP-HTTP adapter](http://docs.php-http.org/en/latest/clients.html), for example [Guzzle6](https://github.com/php-http/guzzle6-adapter) 17 | * A [Geocoder ip-based provider](https://github.com/geocoder-php/Geocoder#ip) 18 | 19 | ## Installation 20 | 21 | This package is installable and autoloadable via Composer as [middlewares/geolocation](https://packagist.org/packages/middlewares/geolocation). 22 | 23 | ```sh 24 | composer require middlewares/geolocation 25 | ``` 26 | 27 | ## Example 28 | 29 | ```php 30 | $freeGeoIpProvider = new Geocoder\Provider\FreeGeoIp($adapter); 31 | 32 | $dispatcher = new Dispatcher([ 33 | new Middlewares\Geolocation($freeGeoIpProvider), 34 | 35 | function ($request) { 36 | //Get the client location 37 | $location = $request->getAttribute('client-location'); 38 | 39 | $country = $location->first()->getCountry(); 40 | } 41 | ]); 42 | 43 | $response = $dispatcher->dispatch(new ServerRequest()); 44 | ``` 45 | 46 | ## Options 47 | 48 | #### `__construct(Geocoder\Provider\Provider $provider)` 49 | 50 | The geocoder provider used to geolocate the client. 51 | 52 | It's also recommended to configure it to [caching responses.](https://github.com/geocoder-php/Geocoder/blob/master/docs/cookbook/cache.md) 53 | 54 | #### `ipAttribute(string $ipAttribute)` 55 | 56 | By default uses the `REMOTE_ADDR` server parameter to get the client ip. This option allows to use a request attribute. Useful to combine with a ip detection middleware, for example [client-ip](https://github.com/middlewares/client-ip). 57 | 58 | #### `attribute(string $attribute)` 59 | 60 | The attribute name used to store the client addresses in the server request. By default is `client-location`. 61 | 62 | --- 63 | 64 | Please see [CHANGELOG](CHANGELOG.md) for more information about recent changes and [CONTRIBUTING](CONTRIBUTING.md) for contributing details. 65 | 66 | The MIT License (MIT). Please see [LICENSE](LICENSE) for more information. 67 | 68 | [ico-version]: https://img.shields.io/packagist/v/middlewares/geolocation.svg?style=flat-square 69 | [ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square 70 | [ico-ga]: https://github.com/middlewares/geolocation/workflows/testing/badge.svg 71 | [ico-downloads]: https://img.shields.io/packagist/dt/middlewares/geolocation.svg?style=flat-square 72 | 73 | [link-packagist]: https://packagist.org/packages/middlewares/geolocation 74 | [link-downloads]: https://packagist.org/packages/middlewares/geolocation 75 | [link-sensiolabs]: https://insight.sensiolabs.com/projects/b6c8bd3a-b3da-45ec-b2ac-9d27ae390b1b 76 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "middlewares/geolocation", 3 | "type": "library", 4 | "description": "Middleware to geolocate the client using the ip address", 5 | "license": "MIT", 6 | "keywords": [ 7 | "psr-7", 8 | "psr-15", 9 | "middleware", 10 | "server", 11 | "http", 12 | "ip", 13 | "geolocation", 14 | "geocode" 15 | ], 16 | "homepage": "https://github.com/middlewares/geolocation", 17 | "support": { 18 | "issues": "https://github.com/middlewares/geolocation/issues" 19 | }, 20 | "require": { 21 | "php": "^7.2 || ^8.0", 22 | "willdurand/geocoder": "^4", 23 | "php-http/message": "^1", 24 | "psr/http-server-middleware": "^1" 25 | }, 26 | "require-dev": { 27 | "phpunit/phpunit": "^8 || ^9", 28 | "friendsofphp/php-cs-fixer": "^3", 29 | "squizlabs/php_codesniffer": "^3", 30 | "middlewares/utils": "^2 || ^3 || ^4", 31 | "php-http/guzzle7-adapter": "^1", 32 | "geocoder-php/free-geoip-provider": "^4", 33 | "phpstan/phpstan": "^1 || ^2", 34 | "laminas/laminas-diactoros": "^2 || ^3", 35 | "oscarotero/php-cs-fixer-config": "^2" 36 | }, 37 | "autoload": { 38 | "psr-4": { 39 | "Middlewares\\": "src/" 40 | } 41 | }, 42 | "autoload-dev": { 43 | "psr-4": { 44 | "Middlewares\\Tests\\": "tests/" 45 | } 46 | }, 47 | "scripts": { 48 | "cs": "phpcs", 49 | "cs-fix": "php-cs-fixer fix", 50 | "phpstan": "phpstan analyse", 51 | "test": "phpunit", 52 | "coverage": "phpunit --coverage-text", 53 | "coverage-html": "phpunit --coverage-html=coverage" 54 | }, 55 | "config": { 56 | "allow-plugins": { 57 | "php-http/discovery": false 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /phpcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | Middlewares coding standard 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | src 15 | tests 16 | 17 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 18 | 19 | 20 | tests 21 | 22 | 23 | 24 | 25 | 26 | ./src 27 | 28 | ./tests 29 | ./vendor 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /src/Geolocation.php: -------------------------------------------------------------------------------- 1 | provider = $provider; 37 | } 38 | 39 | /** 40 | * Set the attribute name to get the client ip. 41 | */ 42 | public function ipAttribute(string $ipAttribute): self 43 | { 44 | $this->ipAttribute = $ipAttribute; 45 | 46 | return $this; 47 | } 48 | 49 | /** 50 | * Set the attribute name to store the geolocation info. 51 | */ 52 | public function attribute(string $attribute): self 53 | { 54 | $this->attribute = $attribute; 55 | 56 | return $this; 57 | } 58 | 59 | /** 60 | * Process a server request and return a response. 61 | */ 62 | public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface 63 | { 64 | $ip = $this->getIp($request); 65 | 66 | if (!empty($ip)) { 67 | $address = $this->getAddress($ip); 68 | $request = $request->withAttribute($this->attribute, $address); 69 | } 70 | 71 | return $handler->handle($request); 72 | } 73 | 74 | /** 75 | * Get the address of an ip 76 | */ 77 | protected function getAddress(string $ip): Collection 78 | { 79 | return $this->provider->geocodeQuery(GeocodeQuery::create($ip)); 80 | } 81 | 82 | /** 83 | * Get the client ip. 84 | */ 85 | private function getIp(ServerRequestInterface $request): string 86 | { 87 | $server = $request->getServerParams(); 88 | 89 | if ($this->ipAttribute !== null) { 90 | return $request->getAttribute($this->ipAttribute); 91 | } 92 | 93 | return isset($server['REMOTE_ADDR']) ? $server['REMOTE_ADDR'] : ''; 94 | } 95 | } 96 | --------------------------------------------------------------------------------