├── .editorconfig ├── .php_cs.dist ├── .travis.yml ├── CONDUCT.md ├── LICENSE ├── README-ES.md ├── README.md ├── composer.json └── src └── Ip.php /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_size = 4 6 | indent_style = space 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | trim_trailing_whitespace = false 13 | -------------------------------------------------------------------------------- /.php_cs.dist: -------------------------------------------------------------------------------- 1 | setRiskyAllowed(true) 4 | ->setRules(array( 5 | '@PSR2' => true, 6 | 'array_syntax' => ['syntax' => 'short'], 7 | 'binary_operator_spaces' => ['align_equals' => false, 'align_double_arrow' => false], 8 | 'blank_line_after_opening_tag' => true, 9 | 'blank_line_after_namespace' => false, 10 | 'blank_line_before_return' => true, 11 | 'cast_spaces' => true, 12 | // 'class_keyword_remove' => true, 13 | 'combine_consecutive_unsets' => true, 14 | 'concat_space' => ['spacing' => 'one'], 15 | 'declare_equal_normalize' => true, 16 | 'declare_strict_types' => false, 17 | 'dir_constant' => true, 18 | 'ereg_to_preg' => true, 19 | 'function_typehint_space' => true, 20 | // 'general_phpdoc_annotation_remove' => ['author', 'category', 'package', 'copyright', 'version'], 21 | 'hash_to_slash_comment' => true, 22 | 'heredoc_to_nowdoc' => true, 23 | 'include' => true, 24 | 'indentation_type' => true, 25 | // 'is_null' => ['use_yoda_style' => false], 26 | 'linebreak_after_opening_tag' => true, 27 | 'lowercase_cast' => true, 28 | // 'mb_str_functions' => true, 29 | 'method_separation' => true, 30 | 'modernize_types_casting' => true, 31 | 'native_function_casing' => true, 32 | // 'native_function_invocation' => true, 33 | 'new_with_braces' => false, // 34 | 'no_alias_functions' => true, 35 | 'no_blank_lines_after_class_opening' => true, 36 | 'no_blank_lines_after_phpdoc' => true, 37 | 'no_blank_lines_before_namespace' => true, 38 | 'no_empty_comment' => true, 39 | 'no_empty_phpdoc' => true, 40 | 'no_empty_statement' => true, 41 | 'no_extra_consecutive_blank_lines' => ['break', 'continue', 'curly_brace_block', 'extra', 'parenthesis_brace_block', 'return', 'square_brace_block', 'throw', 'use', 'useTrait'], 42 | 'no_leading_import_slash' => true, 43 | 'no_leading_namespace_whitespace' => true, 44 | 'no_mixed_echo_print' => ['use' => 'echo'], 45 | 'no_multiline_whitespace_around_double_arrow' => true, 46 | 'no_multiline_whitespace_before_semicolons' => true, 47 | 'no_php4_constructor' => true, 48 | 'no_short_bool_cast' => true, 49 | 'no_short_echo_tag' => false, 50 | 'no_singleline_whitespace_before_semicolons' => true, 51 | 'no_spaces_around_offset' => true, 52 | 'no_trailing_comma_in_list_call' => true, 53 | 'no_trailing_comma_in_singleline_array' => true, 54 | 'no_trailing_whitespace' => true, 55 | 'no_trailing_whitespace_in_comment' => true, 56 | 'no_unneeded_control_parentheses' => true, 57 | 'no_unreachable_default_argument_value' => true, 58 | 'no_unused_imports' => true, 59 | 'no_useless_else' => true, 60 | 'no_useless_return' => true, 61 | 'no_whitespace_before_comma_in_array' => true, 62 | 'no_whitespace_in_blank_line' => true, 63 | 'normalize_index_brace' => true, 64 | 'not_operator_with_space' => false, 65 | 'not_operator_with_successor_space' => true, 66 | 'object_operator_without_whitespace' => true, 67 | 'ordered_class_elements' => true, 68 | 'ordered_imports' => true, 69 | 'php_unit_construct' => true, 70 | 'php_unit_dedicate_assert' => true, 71 | 'php_unit_fqcn_annotation' => true, 72 | 'php_unit_strict' => true, 73 | // 'phpdoc_add_missing_param_annotation' => true, 74 | 'phpdoc_align' => true, 75 | 'phpdoc_annotation_without_dot' => true, 76 | 'phpdoc_indent' => true, 77 | 'phpdoc_inline_tag' => true, 78 | 'phpdoc_no_access' => true, 79 | 'phpdoc_no_alias_tag' => ['property-read' => 'property', 'property-write' => 'property', 'type' => 'var'], 80 | 'phpdoc_no_empty_return' => true, 81 | 'phpdoc_no_package' => true, 82 | // 'phpdoc_no_useless_inheritdoc' => true, 83 | 'phpdoc_order' => true, 84 | 'phpdoc_return_self_reference' => true, 85 | 'phpdoc_scalar' => true, 86 | 'phpdoc_separation' => false, 87 | 'phpdoc_single_line_var_spacing' => true, 88 | // 'phpdoc_summary' => true, 89 | 'phpdoc_to_comment' => true, 90 | 'phpdoc_trim' => true, 91 | 'phpdoc_types' => true, 92 | 'phpdoc_var_without_name' => true, 93 | 'pow_to_exponentiation' => true, 94 | // 'pre_increment' => true, 95 | 'protected_to_private' => true, 96 | 'psr0' => true, 97 | 'psr4' => true, 98 | 'random_api_migration' => true, 99 | 'return_type_declaration' => ['space_before' => 'one'], 100 | 'self_accessor' => true, 101 | 'short_scalar_cast' => true, 102 | // 'silenced_deprecation_error' => true, 103 | // 'simplified_null_return' => true, 104 | 'single_blank_line_before_namespace' => false, 105 | 'single_quote' => true, 106 | 'space_after_semicolon' => true, 107 | 'standardize_not_equals' => true, 108 | // 'strict_comparison' => true, 109 | 'ternary_operator_spaces' => true, 110 | 'strict_param' => true, 111 | 'ternary_to_null_coalescing' => false, 112 | // 'trailing_comma_in_multiline_array' => true, 113 | 'trim_array_spaces' => true, 114 | 'unary_operator_spaces' => true, 115 | 'whitespace_after_comma_in_array' => true 116 | )) 117 | ->setFinder( 118 | PhpCsFixer\Finder::create() 119 | ->in(__DIR__) 120 | )->setLineEnding("\n"); 121 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: php 2 | 3 | sudo: false 4 | 5 | cache: 6 | directories: 7 | - $HOME/.composer/cache 8 | 9 | dist: trusty 10 | 11 | branches: 12 | only: 13 | - master 14 | 15 | git: 16 | depth: 5 17 | 18 | php: 19 | - 5.6 20 | - 7.0 21 | - 7.1 22 | - 7.2 23 | - hhvm 24 | - nightly 25 | 26 | matrix: 27 | fast_finish: true 28 | include: 29 | - php: 7.1 30 | env: PHPCS=PSR2 31 | 32 | allow_failures: 33 | - php: nightly 34 | 35 | before_script: 36 | - export PATH="./vendor/bin:$PATH" 37 | - travis_retry composer self-update 38 | - travis_retry composer install --no-interaction --prefer-source --dev 39 | 40 | script: 41 | - phpunit 42 | - | 43 | if [[ "$PHPCS" ]] ; then 44 | phpcs --standard=phpcs.xml $(find . -name '*.php') 45 | phpmd src,tests text ./phpmd.xml 46 | fi 47 | 48 | after_success: 49 | - bash <(curl -s https://codecov.io/bash) -------------------------------------------------------------------------------- /CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at [INSERT EMAIL ADDRESS]. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | ===================== 3 | 4 | Copyright (c) 2017-2022, Josantonius 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy of 7 | this software and associated documentation files (the "Software"), to deal in 8 | the Software without restriction, including without limitation the rights to 9 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 10 | of the Software, and to permit persons to whom the Software is furnished to do 11 | so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | -------------------------------------------------------------------------------- /README-ES.md: -------------------------------------------------------------------------------- 1 | # PHP Ip library 2 | 3 | [![Latest Stable Version](https://poser.pugx.org/josantonius/Ip/v/stable)](https://packagist.org/packages/josantonius/Ip) 4 | [![License](https://poser.pugx.org/josantonius/Ip/license)](LICENSE) 5 | 6 | [English version](README.md) 7 | 8 | Biblioteca PHP para obtener la IP del usuario. 9 | 10 | >Tras revisar el código después de unos años, no recomendaría el uso de la clase para un sitio en 11 | >producción, ya que se dio preferencia a cabeceras fácilmente manipulables por el usuario para 12 | >obtener la IP. 13 | 14 | >Si la fiabilidad de la cabecera desde la que se obtendrá la IP no está garantizada, sería 15 | >mejor utilizar $_SERVER['REMOTE_ADDR'] directamente o desarrollar una solución personalizada. 16 | 17 | --- 18 | 19 | - [Requisitos](#requisitos) 20 | - [Instalación](#instalación) 21 | - [Métodos disponibles](#métodos-disponibles) 22 | - [Cómo empezar](#cómo-empezar) 23 | - [Uso](#uso) 24 | - [Tests](#tests) 25 | - [Patrocinar](#patrocinar) 26 | - [Licencia](#licencia) 27 | 28 | --- 29 | 30 | ## Requisitos 31 | 32 | Esta clase es soportada por versiones de **PHP 5.6** o superiores y es compatible con versiones de **HHVM 3.0** o superiores. 33 | 34 | ## Instalación 35 | 36 | La mejor forma de instalar esta extensión es a través de [Composer](http://getcomposer.org/download/). 37 | 38 | Para instalar **PHP Ip library**, simplemente escribe: 39 | 40 | composer require Josantonius/Ip 41 | 42 | El comando anterior sólo instalará los archivos necesarios, si prefieres **descargar todo el código fuente** puedes utilizar: 43 | 44 | composer require Josantonius/Ip --prefer-source 45 | 46 | También puedes **clonar el repositorio** completo con Git: 47 | 48 | $ git clone 49 | 50 | O **instalarlo manualmente**: 51 | 52 | [Descargar Ip.php](https://raw.githubusercontent.com/Josantonius/PHP-Ip/master/src/Ip.php): 53 | 54 | wget https://raw.githubusercontent.com/Josantonius/PHP-Ip/master/src/Ip.php 55 | 56 | ## Métodos disponibles 57 | 58 | Métodos disponibles en esta biblioteca: 59 | 60 | ### - Obtener IP del usuario 61 | 62 | ```php 63 | Ip::get(); 64 | ``` 65 | 66 | **# Return** (string|false) → IP o falso 67 | 68 | ### - Validar IP 69 | 70 | ```php 71 | Ip::validate($ip); 72 | ``` 73 | 74 | | Atributo | Descripción | Tipo | Requerido | Predeterminado 75 | | --- | --- | --- | --- | --- | 76 | | $ip | Dirección IP a validar. | string | Sí | | 77 | 78 | **# Return** (boolean) 79 | 80 | ## Cómo empezar 81 | 82 | Para utilizar esta biblioteca con **Composer**: 83 | 84 | ```php 85 | require __DIR__ . '/vendor/autoload.php'; 86 | 87 | use Josantonius\Ip\Ip; 88 | ``` 89 | 90 | Si la instalaste **manualmente**, utiliza: 91 | 92 | ```php 93 | require_once __DIR__ . '/Ip.php'; 94 | 95 | use Josantonius\Ip\Ip; 96 | ``` 97 | 98 | ## Uso 99 | 100 | Ejemplo de uso para esta biblioteca: 101 | 102 | ### - Obtener IP del usuario 103 | 104 | ```php 105 | Ip::get(); 106 | ``` 107 | 108 | ### - Validar IP 109 | 110 | ```php 111 | $ip = Ip::get(); 112 | 113 | Ip::validate($ip); 114 | ``` 115 | 116 | ## Tests 117 | 118 | Para ejecutar las [pruebas](tests) necesitarás [Composer](http://getcomposer.org/download/) y seguir los siguientes pasos: 119 | 120 | git clone https://github.com/Josantonius/PHP-Ip.git 121 | 122 | cd PHP-Ip 123 | 124 | composer install 125 | 126 | Ejecutar pruebas unitarias con [PHPUnit](https://phpunit.de/): 127 | 128 | composer phpunit 129 | 130 | Ejecutar pruebas de estándares de código [PSR2](http://www.php-fig.org/psr/psr-2/) con [PHPCS](https://github.com/squizlabs/PHP_CodeSniffer): 131 | 132 | composer phpcs 133 | 134 | Ejecutar pruebas con [PHP Mess Detector](https://phpmd.org/) para detectar inconsistencias en el estilo de codificación: 135 | 136 | composer phpmd 137 | 138 | Ejecutar todas las pruebas anteriores: 139 | 140 | composer tests 141 | 142 | ## Patrocinar 143 | 144 | Si este proyecto te ayuda a reducir el tiempo de desarrollo, 145 | [puedes patrocinarme](https://github.com/josantonius/lang/es-ES/README.md#patrocinar) 146 | para apoyar mi trabajo :blush: 147 | 148 | ## Licencia 149 | 150 | Este repositorio tiene una licencia [MIT License](LICENSE). 151 | 152 | Copyright © 2017-2022, [Josantonius](https://github.com/josantonius/lang/es-ES/README.md#contacto) 153 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PHP Ip library 2 | 3 | [![Latest Stable Version](https://poser.pugx.org/josantonius/Ip/v/stable)](https://packagist.org/packages/josantonius/Ip) 4 | [![License](https://poser.pugx.org/josantonius/Ip/license)](LICENSE) 5 | 6 | [Versión en español](README-ES.md) 7 | 8 | PHP class to get user IP. 9 | 10 | >After reviewing the code after a few years, I would not recommend the use of the class for a 11 | >production site, as preference was given to headers easily manipulated by the user to get the IP. 12 | 13 | >If the reliability of the header from which the IP will be obtained is not guaranteed, 14 | >it is better to use $_SERVER['REMOTE_ADDR'] directly or develop a custom solution. 15 | 16 | --- 17 | 18 | - [Requirements](#requirements) 19 | - [Installation](#installation) 20 | - [Available Methods](#available-methods) 21 | - [Quick Start](#quick-start) 22 | - [Usage](#usage) 23 | - [Tests](#tests) 24 | - [Sponsor](#Sponsor) 25 | - [License](#license) 26 | 27 | --- 28 | 29 | ## Requirements 30 | 31 | This library is supported by **PHP versions 5.6** or higher and is compatible with **HHVM versions 3.0** or higher. 32 | 33 | ## Installation 34 | 35 | The preferred way to install this extension is through [Composer](http://getcomposer.org/download/). 36 | 37 | To install **PHP Ip library**, simply: 38 | 39 | composer require Josantonius/Ip 40 | 41 | The previous command will only install the necessary files, if you prefer to **download the entire source code** you can use: 42 | 43 | composer require Josantonius/Ip --prefer-source 44 | 45 | You can also **clone the complete repository** with Git: 46 | 47 | $ git clone 48 | 49 | Or **install it manually**: 50 | 51 | [Download Ip.php](https://raw.githubusercontent.com/Josantonius/PHP-Ip/master/src/Ip.php): 52 | 53 | wget https://raw.githubusercontent.com/Josantonius/PHP-Ip/master/src/Ip.php 54 | 55 | ## Available Methods 56 | 57 | Available methods in this library: 58 | 59 | ### - Get user's IP 60 | 61 | ```php 62 | Ip::get(); 63 | ``` 64 | 65 | **# Return** (string|false) → user IP or false 66 | 67 | ### - Validate IP 68 | 69 | ```php 70 | Ip::validate($ip); 71 | ``` 72 | 73 | | Attribute | Description | Type | Required | Default 74 | | --- | --- | --- | --- | --- | 75 | | $ip | IP address to be validated. | string | Yes | | 76 | 77 | **# Return** (boolean) 78 | 79 | ## Quick Start 80 | 81 | To use this library with **Composer**: 82 | 83 | ```php 84 | require __DIR__ . '/vendor/autoload.php'; 85 | 86 | use Josantonius\Ip\Ip; 87 | ``` 88 | 89 | Or If you installed it **manually**, use it: 90 | 91 | ```php 92 | require_once __DIR__ . '/Ip.php'; 93 | 94 | use Josantonius\Ip\Ip; 95 | ``` 96 | 97 | ## Usage 98 | 99 | Example of use for this library: 100 | 101 | ### - Get user's IP 102 | 103 | ```php 104 | Ip::get(); 105 | ``` 106 | 107 | ### - Validate IP 108 | 109 | ```php 110 | $ip = Ip::get(); 111 | 112 | Ip::validate($ip); 113 | ``` 114 | 115 | ## Tests 116 | 117 | To run [tests](tests) you just need [composer](http://getcomposer.org/download/) and to execute the following: 118 | 119 | git clone https://github.com/Josantonius/PHP-Ip.git 120 | 121 | cd PHP-Ip 122 | 123 | composer install 124 | 125 | Run unit tests with [PHPUnit](https://phpunit.de/): 126 | 127 | composer phpunit 128 | 129 | Run [PSR2](http://www.php-fig.org/psr/psr-2/) code standard tests with [PHPCS](https://github.com/squizlabs/PHP_CodeSniffer): 130 | 131 | composer phpcs 132 | 133 | Run [PHP Mess Detector](https://phpmd.org/) tests to detect inconsistencies in code style: 134 | 135 | composer phpmd 136 | 137 | Run all previous tests: 138 | 139 | composer tests 140 | 141 | ## Sponsor 142 | 143 | If this project helps you to reduce your development time, 144 | [you can sponsor me](https://github.com/josantonius#sponsor) to support my open source work :blush: 145 | 146 | ## License 147 | 148 | This repository is licensed under the [MIT License](LICENSE). 149 | 150 | Copyright © 2017-2022, [Josantonius](https://github.com/josantonius#contact) 151 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "josantonius/ip", 3 | "type": "library", 4 | "description": "PHP class to get user IP.", 5 | "keywords": [ 6 | "IP", 7 | "Get user IP", 8 | "REMOTE_ADDR", 9 | "HHVM", 10 | "PHP" 11 | ], 12 | "license": "MIT", 13 | "authors": [ 14 | { 15 | "name": "Josantonius", 16 | "email": "hello@josantonius.com", 17 | "homepage": "https://josantonius.com", 18 | "role": "Developer" 19 | } 20 | ], 21 | "support": { 22 | "issues": "https://github.com/josantonius/php-ip/issues", 23 | "forum": "http://stackoverflow.com/tags/josantonius/php-ip", 24 | "source": "https://github.com/josantonius/php-ip" 25 | }, 26 | "config": { 27 | "preferred-install": "dist" 28 | }, 29 | "minimum-stability": "stable", 30 | "require": { 31 | "php": "^5.6 || ^7.0" 32 | }, 33 | "require-dev": { 34 | "phpunit/phpunit": "^5.7 || ^6.0", 35 | "squizlabs/php_codesniffer": "^3.0", 36 | "friendsofphp/php-cs-fixer": "^2.3 || ^2.8", 37 | "phpmd/phpmd": "^2.6" 38 | }, 39 | "autoload": { 40 | "psr-4": { 41 | "Josantonius\\Ip\\": "src/" 42 | } 43 | }, 44 | "autoload-dev": { 45 | "psr-4": { 46 | "Josantonius\\Ip\\": "tests/" 47 | } 48 | }, 49 | "extra": { 50 | "branch-alias": { 51 | "dev-master": "1.0-dev" 52 | } 53 | }, 54 | "scripts": { 55 | "phpunit": "vendor/bin/phpunit --colors=always;", 56 | "phpcs": "vendor/bin/phpcs --standard=phpcs.xml $(find . -name '*.php');", 57 | "phpmd": "vendor/bin/phpmd src,tests text ./phpmd.xml", 58 | "fix": [ 59 | "vendor/bin/php-cs-fixer fix -v", 60 | "vendor/bin/phpcbf src tests" 61 | ], 62 | "tests": [ 63 | "clear", 64 | "@phpmd", 65 | "@phpcs", 66 | "@phpunit" 67 | ] 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/Ip.php: -------------------------------------------------------------------------------- 1 | 6 | * @author Josantonius - 7 | * @copyright 2017 - 2018 (c) Josantonius - PHP-Ip 8 | * @license https://opensource.org/licenses/MIT - The MIT License (MIT) 9 | * @link https://github.com/Josantonius/PHP-Ip 10 | * @since 1.0.0 11 | */ 12 | namespace Josantonius\Ip; 13 | 14 | /** 15 | * IP handler. 16 | */ 17 | class Ip 18 | { 19 | /** 20 | * Get user's IP. 21 | * 22 | * @return string|false → user IP 23 | */ 24 | public static function get() 25 | { 26 | $possibleKeys = [ 27 | 'HTTP_X_FORWARDED_FOR', 28 | 'HTTP_X_FORWARDED', 29 | 'HTTP_X_CLUSTER_CLIENT_IP', 30 | 'HTTP_FORWARDED_FOR', 31 | 'HTTP_FORWARDED', 32 | 'HTTP_VIA', 33 | 'HTTP_X_COMING_FROM', 34 | 'HTTP_COMING_FROM', 35 | 'HTTP_X_REAL_IP', 36 | 'REMOTE_ADDR', 37 | ]; 38 | 39 | foreach ($possibleKeys as $key) { 40 | if ($ip = static::getGlobalValue($key)) { 41 | return $ip; 42 | } 43 | } 44 | 45 | return false; 46 | } 47 | 48 | /** 49 | * Validate IP. 50 | * 51 | * @since 1.1.2 52 | * 53 | * @param string $ip → IP address to be validated 54 | * 55 | * @return bool 56 | */ 57 | public static function validate($ip) 58 | { 59 | return filter_var($ip, FILTER_VALIDATE_IP) ? true : false; 60 | } 61 | 62 | /** 63 | * Gets the key value from globals. 64 | * 65 | * @since 1.1.4 66 | * 67 | * @param string $key 68 | * 69 | * @return string|null 70 | */ 71 | protected static function getGlobalValue($key) 72 | { 73 | if (isset($_SERVER[$key]) && static::validate($_SERVER[$key])) { 74 | return $_SERVER[$key]; 75 | } 76 | 77 | if (isset($_ENV[$key]) && static::validate($_ENV[$key])) { 78 | return $_ENV[$key]; 79 | } 80 | 81 | if (@getenv($key) && static::validate(getenv($key))) { 82 | return getenv($key); 83 | } 84 | 85 | return null; 86 | } 87 | } 88 | --------------------------------------------------------------------------------