Krajee

Ip Info

Thankful to Krajee! BUY A COFFEEor to get more out of us.
An IP address information display widget for Yii framework 2.0 with ability to display country flag and geo position info. This is based on the HTTP API from from ipstack.com (earlier freegeoip.net) to parse IP address details. The plugin also uses the yii2-popover-x extension by Krajee for displaying details of the IP in a popover and the yii2-icons extension by Krajee for displaying the flag icons. The widget offers these various features:
  • Ability to display the flag for a IP address.

  • Ability to display geo position details for the IP address.

  • Ability to render IP details inline instead of popover.

  • Ability to configure fields rendered and also control the layout with templates.

  • Use yii2-popover-x extension features to control popover placements and styles.

  • Use flag icons from yii2-icons to render country wise high resolution flags of any size.

  • Uses Yii i18N translations to generate locale specific data.

Tip

Not seeing the updated content on this page! Hard refresh your browser to clean cache for this page (e.g. SHIFT-F5 on Windows Chrome)

IpInfo supports configuration of the bootstrap library version so that you can use this either with any Bootstrap version 3.x and above. For setting up the bootstrap version for your extension, you can configure the IpInfo::bsVersion property to one of the following.

  • To use with bootstrap 3 library - you can set IpInfo::bsVersion property to any string starting with 3 (e.g. 3 or 3.3.7 or 3.x)

  • To use with bootstrap 4 library - you can set IpInfo::bsVersion property to any string starting with 4 (e.g. 4 or 4.6.0 or 4.x)

  • To use with bootstrap 5 library - you can set IpInfo::bsVersion property to any string starting with 5 (e.g. 5 or 5.1.0 or 5.x)

The following sections describe the pre-requisites for enabling Bootstrap library specific version support in your application and other related controls/overrides.

Global Bootstrap Version


Generally, you may also want to set a default version globally for all Krajee Extensions (instead of setting it for each widget or extension separately). In order to do this, you can setup the bsVersion property within Yii 2 application params (i.e. Yii::$app->params['bsVersion']). To set this up, add this section of code to your application params configuration file (e.g. config/params.php):

'params' => [
    'bsVersion' => '5.x', // this will set globally `bsVersion` to Bootstrap 5.x for all Krajee Extensions
    // other settings
    // 'adminEmail' => 'admin@example.com'
]

If IpInfo::bsVersion property is set, in addition to Yii::$app->params['bsVersion'], the extension level setting (IpInfo::bsVersion property) will override the Yii::$app->params['bsVersion']. If IpInfo::bsVersion property is not set, and Yii::$app->params['bsVersion'] is also not set, IpInfo::bsVersion property will default to 3.x (i.e. Bootstrap 3.x version will be assumed as default).

Yii2 Bootstrap Dependency


You need to install one of yiisoft/yii2-bootstrap or yiisoft/yii2-bootstrap4 or yiisoft/yii2-bootstrap5 extensions manually in your application to enable Bootstrap 3.x or 4.x or 5.x functionality respectively. This dependency has not been pre-built into the composer configuration for Krajee extensions, to allow better control to the developers in configuring their bootstrap library version. If bsVersion is set to 5.x and yiisoft/yii2-bootstrap5 is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap5 extension. If bsVersion is set to 4.x and yiisoft/yii2-bootstrap4 is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap4 extension. Similarly, if bsVersion is set to 3.x and yiisoft/yii2-bootstrap is not installed, an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap extension.

To install yiisoft/yii2-bootstrap5, add the repo to the require section of your application's composer.json.

"yiisoft/yii2-bootstrap5": "@dev"

To install yiisoft/yii2-bootstrap4, add the repo to the require section of your application's composer.json.

"yiisoft/yii2-bootstrap4": "@dev"

To install yiisoft/yii2-bootstrap, add the repo to the require section of your application's composer.json.

"yiisoft/yii2-bootstrap": "@dev"

Override Bootstrap CSS/JS


The Krajee extension asset bundle(s) by default depend on one of the following asset bundles to load the Bootstrap CSS and JS:

  • yii\bootstrap\BootstrapAsset and/or yii\bootstrap\BootstrapPluginAsset for bootstrap 3.x (bsVersion = 3 setting)

  • yii\bootstrap4\BootstrapAsset and/or yii\bootstrap4\BootstrapPluginAsset for bootstrap 4.x ( bsVersion = 4 setting)

  • yii\bootstrap5\BootstrapAsset and/or yii\bootstrap5\BootstrapPluginAsset for bootstrap 5.x (bsVersion = 5 setting)

This is controlled by the property bsDependencyEnabled within the asset bundle (which defaults to true). One can override this and prevent the default yii2 bootstrap assets (CSS & JS) from loading by doing one or all of the following:

  • Global Override: Set Yii::$app->params['bsDependencyEnabled'] to false in your Yii 2 application config params.php. This setting will be applied for all Krajee Extension Asset Bundles that depend on Bootstrap assets.

    'params' => [
        'bsDependencyEnabled' => false, // this will not load Bootstrap CSS and JS for all Krajee extensions
        // you need to ensure you load the Bootstrap CSS/JS manually in your view layout before Krajee CSS/JS assets
        //
        // other params settings below
        // 'bsVersion' => '5.x',
        // 'adminEmail' => 'admin@example.com'
    ]
    
  • Asset Bundle Specific Override: Set bsDependencyEnabled to false for the specific asset bundle within Yii2 Asset Manager component in your Yii 2 application config file.

    // ...
    'components' => [
        'assetManager' => [
            'bundles' => [
                'kartik\form\ActiveFormAsset' => [
                    'bsDependencyEnabled' => false // do not load bootstrap assets for a specific asset bundle
                ],
            ],
        ],
    ],
    

Note

When setting bsDependencyEnabled to false, you need to ensure that your app code/view layout loads the Bootstrap CSS and JS on your view before the Krajee CSS/JS are loaded to ensure that the Krajee extension JS plugins and CSS styles do not get broken.

Icons for Bootstrap


Bootstrap 5.x / 4.x does not include glyphicons or any other icons framework bundled with the library. Krajee extensions therefore will use Font Awesome 5.x icons instead of glyphicons when working with Bootstrap 5.x / 4.x. You can download Font Awesome 5.x icons from the icons website. Alternatively, you can load the free version of Font Awesome from their CDN.

For Krajee extensions and demos, the Font Awesome Free version is used and loaded as the Icons Display Package on all the Yii2 demo layouts. To include font awesome assets on your page, include the following markup on the HEAD section of your view layout file, when bsVersion is set to 4.x or 5.x.

  • Option 1: Font CSS version of Font Awesome:

    <!-- on your view layout file HEAD section -->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css">
    
  • Option 2: SVG / JS version of Font Awesome (recommended for cleaner scaling vector icons and features like icon layers):

    <!-- on your view layout file HEAD section -->
    <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js" crossorigin="anonymous"></script>
    

    Alternatively, you can use the FontAwesomeAsset from the kartik-v/yii2-icons package to load the SVG/JS version.

    // on your view layout file
    use kartik\icons\FontAwesomeAsset;
    FontAwesomeAsset::register($this);
    

The yii2-ipinfo extension can be installed automatically or manually using one of these options:

Composer Package Manager Recommended


Installation via Composer is the recommended and most easy option to install Krajee Yii2 extensions. You can install yii2-ipinfo via composer package manager. Either run:

$ php composer.phar require kartik-v/yii2-ipinfo "dev-master"

or add:

"kartik-v/yii2-ipinfo": "dev-master"

to your application's composer.json file.

Manual Install


You may also manually install the extension to your project (in case your composer install does not work). Just download the source ZIP or TAR ball and extract the extension asset files and folders into your project. You may need to install dependencies manually and also set the namespaces to the extensions in your Yii2 extensions configurations manually.

The IpInfo widget supports the following properties:

bsVersion

string | int, the bootstrap library version to be used for the extension. Refer the Bootstrap Info section for details and pre-requisites on setting this property.

  • To use with Bootstrap library - you can set this to any string starting with 3 (e.g. 3 or 3.3.7 or 4.x / 3.x)

  • To use with bootstrap 4 - you can set this to any string starting with 4 (e.g. 4 or 4.6.0 or 4.x)

  • To use with bootstrap 5 - you can set this to any string starting with 4 (e.g. 5 or 5.1.0 or 5.x)

bsColCssPrefixes

array, the bootstrap grid column css prefixes mapping, the key is the bootstrap versions, and the value is an array containing the sizes and their corresponding grid column css prefixes. The class using this trait, must implement kartik\base\BootstrapInterface. If not set will default to:.

[
   3 => [
      self::SIZE_X_SMALL => 'col-xs-',
      self::SIZE_SMALL => 'col-sm-',
      self::SIZE_MEDIUM => 'col-md-',
      self::SIZE_LARGE => 'col-lg-',
      self::SIZE_X_LARGE => 'col-lg-',
      self::SIZE_XX_LARGE => 'col-lg-',
   ],
   4 => [
      self::SIZE_X_SMALL => 'col-',
      self::SIZE_SMALL => 'col-sm-',
      self::SIZE_MEDIUM => 'col-md-',
      self::SIZE_LARGE => 'col-lg-',
      self::SIZE_X_LARGE => 'col-xl-',
      self::SIZE_XX_LARGE => 'col-xl-',
   ],
   5 => [
      self::SIZE_X_SMALL => 'col-',
      self::SIZE_SMALL => 'col-sm-',
      self::SIZE_MEDIUM => 'col-md-',
      self::SIZE_LARGE => 'col-lg-',
      self::SIZE_X_LARGE => 'col-xl-',
      self::SIZE_XX_LARGE => 'col-xxl-',
   ],
];

api

string, the api used for fetching the IP information in json format. Defaults to https://ip-api.com/json/{ip}. Note that this default API service from ip-api is free only for non commercial use. The token {ip} in the API url will be replaced with the source ip address set in ip. You can override this to any other IP API service of your choice. You may need to change the fields, modelClass and detailViewConfig to match your choice.

ip

string, the ip address. If this is not set, the current request user's ip address will be used.

modelClass

string, the model class used for rendering the ip information. Defaults to \kartik\ipinfo\IpInfoModel. To use your own API service or to customize the model, you can extend \kartik\ipinfo\IpInfoModel and set it to your own modelClass.

detailViewClass

string, the Yii2 Detail View widget class used for rendering the ip details information in a tabular form. Defaults to \yii\widgets\DetailView.

detailViewConfig

array, the configuration of the Detail View widget class used for rendering the ip details information in a tabular form. Defaults to \yii\widgets\DetailView.

detailRowOptions

array, the HTML attributes for each detail view table row.

params

array, any additional query or request parameters to pass to the IP API set via api.

requestConfig

array, the default Yii2 HTTP Client request configuration.

cache

boolean, whether to cache ip information in the server cache for the session. If set to true, the Yii2 application cache component will be used for caching. If Yii2 caching component is not set or disabled, the caching will be ignored silently without any exceptions. Using caching, will optimize and reduce server api calls for ip addresses already parsed in the past.

If this is set to true, ensure you have configured the cache component in your Yii2 configuration file similar to the example shown below:

'components' => [
    'cache' => [
        'class' => 'yii\caching\FileCache', // or any other caching component you desire with other settings
    ]
]

template

array, the template configuration for rendering the popover button, popover content, or inline content. This should be set as $key => $value pairs, where $key is one of:

  • popoverButton: this is the template for popover button label (applied when showPopover is true)

  • popoverContent: this is the template for popover content displayed on click of the button (applied when showPopover is true).

  • inlineContent: this is the template for inline content when showPopover is set to false.

The $value is the template setting and can contain tags in braces, which will represent value of each IP position field (set in fields property) fetched from the https://ip-api.com/ API (for example {country_code}, {country_name} etc.). The following additional special tags will be replaced:

  • {flag}: Will be replaced with the flag icon rendered based on the showFlag setting.

  • {table}: Will render all fields configured via fields in a tabular format of labels and values.

showFlag

boolean, whether to display the country flag in one of the main template sections (defined in template) by parsing the ip address. Defaults to true.

showPopover

boolean, whether to show position details in a popover on click of the flag. If set to false, the results will be rendered inline. Defaults to true. This will use the yii2-popover-x extension by Krajee for rendering the popover.

hideEmpty

boolean, whether to hide / skip display of fields in the Detail View which have empty values (null or empty). Defaults to true.

errorData

array, the markup to be displayed when any exception is faced during processing by the API (e.g. no connectivity). You can set this to a blank string to not display anything. The following tokens will be replaced:

  • {errorIcon}: with the icon markup set in errorIcon.

  • {message}: any error message returned by api.

errorDataOptions

array, the HTML attributes for error data container. Defaults to: ['title' => 'IP fetch error']. The following special tags are recognized:

  • tag: string, the HTML tag in which the content will be rendered. Defaults to div.

inlineContentOptions

array, the HTML attributes for container when rendering inline.

noData

string, the message to be displayed when no valid data is found. Defaults to Yii2 translated message:

No data found for IP address {ip}.

This can be referred as {noData} token in any of the templates.

fields

array, the list of names of fields / attributes to be shown in tabular display. If this is not set all attributes from modelClass will be shown (the hideEmpty setting will control whether to hide attributes that have an empty value). Defaults to the following attribute names:

[
    'ip',
    'continentCode',
    'continent',
    'countryCode',
    'country',
    'flag',
    'region',
    'regionName',
    'city',
    'district',
    'zip',
    'lat',
    'lon',
    'timezone',
    'currency',
    'isp',
    'org',
    'as',
    'asname',
    'reverse',
    'mobile',
    'proxy',
]

fields

array, the list of names of fields/ attributes which will be skipped from tabular display. Defaults to empty array (which means no fields will be skipped from display). Note that this setting will override the fields setting.

popoverOptions

array, the widget configuration settings for the kartik\popover\PopoverX widget that will display the ip information details in tabular format on button click / hover when showPopover is set to true.

flagWrapperOptions

array, the HTML attributes for the flag wrapper container.

flagOptions

array, the HTML attributes for the flag image (rendered via flag-icon-css in kartik-v/yii2-icons).

contentHeader

string, the header title for content shown in the popover. Defaults to Yii2 translated message:

IP Position Details

errorIcon

string, the error icon shown for any error in the IP fetch by API. Defaults to:

  • <i class="fas fa-exclamation-sign text-danger"></i> when bsVersion is set to 3.x.

  • <i class="fas fa-exclamation-circle text-danger"></i> when bsVersion is set to 4.x or 5.x.

contentHeaderIcon

string, the icon shown before the header title for content in the popover. Defaults to:

  • <i class="fas fa-map-marker"></i> when bsVersion is set to 3.x.

  • <i class="fas fa-map-marker-alt"></i> when bsVersion is set to 4.x or 5.x.

noFlagIcon

string, the icon shown when no flag is found. Defaults to:

  • <i class="fas fa-question-sign text-warning"></i> when bsVersion is set to 3.x.

  • <i class="fas fa-question-circle text-warning"></i> when bsVersion is set to 4.x or 5.x.

options

array, the HTML attributes for the widget container. The following special tags are recognized:

  • tag: string, the HTML tag in which the content will be rendered. Defaults to div.

Basic default usage without any options. When ip is not set, the IP address of the user session will be used to determine the IP info. Click the flag icon to get details.

Show details for a specific ip address and style your popover toggle button. Display details in a popover on clicking the flag icon. Control popover styles and layout by setting popoverOptions.

Expand example above to configure your own template for displaying additional field content in the toggle button

IP Address3.133.123.162
Country US - United States
RegionOH - Ohio
CityDublin
Zip43017
Latitude40° 5' 57''
Longitude6' 51''
Time ZoneAmerica/New_York
ISPAmazon.com, Inc.
OrganizationAWS EC2 (us-east-2)
ASAS16509 Amazon.com, Inc.
Hide popover and display the results inline. Set your table CSS styles if needed.

IP Address3.133.123.162
Country US - United States
RegionOH - Ohio
CityDublin
Zip43017
Latitude40° 5' 57''
Longitude6' 51''
Time ZoneAmerica/New_York
ISPAmazon.com, Inc.
OrganizationAWS EC2 (us-east-2)
ASAS16509 Amazon.com, Inc.
Display a full size flag for the same example above.

You are logged in from
IP Address3.133.123.162
Country US - United States
RegionOH - Ohio
CityDublin
Zip43017
Hide flag and display results inline. Configure skipFields to skip fields you do not need to display.

Dublin US
Configure template for inline layout without popover (for example show flag, city, and countryCode)
use kartik\ipinfo\IpInfo;
use kartik\popover\PopoverX;

// Basic default usage without any options. When <code>ip</code> is not set, the IP address of 
// the user session will be used to determine the IP info. Click the flag icon to get details.
echo IpInfo::widget();

// Show details for a specific ip address and style your popover toggle button. Display details
// in a popover on clicking the flag icon. Control popover styles and layout by setting 
// `popoverOptions`.
echo IpInfo::widget([
    'ip' => '5.56.191.105',
    'popoverOptions' => [
        'toggleButton' => ['class' => 'btn btn-secondary btn-default btn-lg'],
        'placement' => PopoverX::ALIGN_BOTTOM_LEFT
    ]
]);

// Expand example above to configure your own template for displaying additional field content
// in the toggle button
echo IpInfo::widget([
    'ip' => '12.23.155.123',
    'template' => ['popoverButton'=>'{flag} ({city}, {region} - {zip}, {country})'],
    'popoverOptions' => [
        'placement' => PopoverX::ALIGN_BOTTOM_LEFT,
    ]
]);

// Hide popover and display the results inline. Set your table CSS styles if needed.
echo IpInfo::widget([  
    'showPopover' => false,
    'flagWrapperOptions' => ['class' => 'kv-flag-center', 'style'=>'width:100px;height:75px;'],
    'flagOptions' => ['class' => 'kv-flag-bordered flag-icon'],
]);

// Display a full size flag for the same example above
echo IpInfo::widget([ 
    'showPopover' => false, 
    'flagWrapperOptions' => ['class' => 'kv-flag-wrapper'],
    'flagOptions' => ['class' => 'img-thumbnail flag flag-icon-background']
]);

// Hide flag and display results inline. Configure <code>fields</code> to reorder fields and only
// show the column fields you need to display by configuring fields to skip via `skipFields`.
echo IpInfo::widget([
    'showFlag' => false,
    'showPopover' => false,
    'skipFields' => ['lat', 'lon', 'timezone', 'isp', 'org', 'as'],
]);

// Configure template for inline layout without popover (for example show
// `flag`, `city`, and `country_code`)
echo IpInfo::widget([
    'showPopover' => false,
    'template' => ['inlineContent'=>'{flag} {city} {countryCode}'],
]);

yii2-ipinfo is released under the BSD-3-Clause License. See the bundled LICENSE.md for details.

Note

You can now visit the Krajee Webtips Q & A forum for searching OR asking questions OR helping programmers with answers on these extensions and plugins. For asking a question click here. Select the appropriate question category (i.e. Krajee Plugins) and choose this current page plugin in the question related to field.

The comments and discussion section below are intended for generic discussions or feedback for this plugin. Developers may not be able to search or lookup here specific questions or tips on usage for this plugin.

 
visitors to Krajee Yii2 Demos since 22-May-2017