Skip to main content

Get visitor IP address in PHP.

<?php

/**
 * Get key value from Array
 *
 * @param array $array The array to search.
 * @param mixed $key The array key to match.
 * @param mixed $value The default value to return if the key's value is not
 *                     found. The default value is null if not set.
 *
 * @return mixed The matched key value.
 */
function _arrayValue($array, $key, $value = null)
{
    if (!empty($array[$key]))
    {
        $value = $array[$key];
    }

    return $value;
}

/**
 * Get vistor IP address
 *
 * @return mixed The visitor IP address.
 */
function getVisitIp()
{
    $matchIp = '/^([0-9]{1,3}\.){3}[0-9]{1,3}$/';

    $ipKeys = array(
        'HTTP_X_FORWARDED_FOR',
        'HTTP_CLIENT_IP',
        'HTTP_CF_CONNECTING_IP',
    );

    foreach ($ipKeys as $ipKey)
    {
        if (isset($_SERVER[$ipKey])
            && preg_match($matchIp, $_SERVER[$ipKey]))
        {
            return $_SERVER[$ipKey];
        }
    }

    return _arrayValue($_SERVER, 'REMOTE_ADDR');
}