Skip to content

Commit

Permalink
Added IP2Proxy web service.
Browse files Browse the repository at this point in the history
  • Loading branch information
ip2location committed Mar 26, 2020
1 parent 7b325e4 commit 2049b73
Show file tree
Hide file tree
Showing 3 changed files with 208 additions and 12 deletions.
52 changes: 51 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ This module allows user to query an IP address if it was being used as open prox
## Methods
Below are the methods supported in this class.



### BIN Database Class

|Method Name|Description|
|---|---|
|open|Open the IP2Proxy BIN data for lookup. Please see the **Usage** section of the 3 modes supported to load the BIN data file.|
Expand All @@ -31,15 +35,29 @@ Below are the methods supported in this class.
|getAS|Autonomous system (AS) name.|
|getLastSeen|Proxy last seen in days.|



### Web Service Class

| Method Name | Description |
| ----------- | ------------------------------------------------------------ |
| Constructor | Expect 3 input parameters:<ol><li>IP2Proxy API Key.</li><li>Package (PX1 - PX8)</li><li>Use HTTPS or HTTP</li></ol> |
| lookup | Return the proxy information in array.<ul><li>countryCode</li><li>countryName</li><li>regionName</li><li>cityName</li><li>isp</li><li>domain</li><li>usageType</li><li>asn</li><li>as</li><li>lastSeen</li><li>proxyType</li><li>isProxy</li></ul> |
| getCredit | Return remaining credit of the web service account. |



## Usage

### BIN Database

Open and read IP2Proxy binary database. There are 3 modes:

1. **\IP2Proxy\Database::FILE_IO** - File I/O reading. Slower look, but low resource consuming.
2. **\IP2Proxy\Database::MEMORY_CACHE** - Caches database into memory for faster lookup. Required high memory.
3. **\IP2Proxy\Database::SHARED_MEMORY** - Stores whole IP2Proxy database into system memory. Lookup is possible across all applications within the system. Extremely resources consuming. Do not use this mode if your system do not have enough memory.

```
```php
require 'class.IP2Proxy.php';

$db = new \IP2Proxy\Database();
Expand Down Expand Up @@ -95,6 +113,38 @@ echo '<p><strong>Last Seen: </strong>' . $lastSeen . '</p>';

Note: if you are getting error such as `Call to undefined function IP2Proxy\gmp_import()`, you probably did not have the module to install or enable in php.ini. You can check your php.ini to make sure that the module has been enabled.

### Web Service API

To lookup by Web service, you will need to sign up for [IP2Proxy Web Service](https://www.ip2location.com/web-service/ip2proxy) to get a API key.

Start your lookup by following codes:

```php
require 'class.IP2Proxy.php';

// Lookup by Web API
$ws = new \IP2Proxy\WebService('YOUR_API_KEY', 'PX8', false);

$results = $ws->lookup('1.0.241.135');

if ($results !== false) {
echo '<p><strong>Country Code: </strong>' . $results['countryCode'] . '</p>';
echo '<p><strong>Country Name: </strong>' . $results['countryName'] . '</p>';
echo '<p><strong>Region: </strong>' . $results['regionName'] . '</p>';
echo '<p><strong>City: </strong>' . $results['cityName'] . '</p>';
echo '<p><strong>ISP: </strong>' . $results['isp'] . '</p>';
echo '<p><strong>Domain: </strong>' . $results['domain'] . '</p>';
echo '<p><strong>Usage Type: </strong>' . $results['usageType'] . '</p>';
echo '<p><strong>ASN: </strong>' . $results['asn'] . '</p>';
echo '<p><strong>AS: </strong>' . $results['as'] . '</p>';
echo '<p><strong>Last Seen: </strong>' . $results['lastSeen'] . ' Day(s)</p>';
echo '<p><strong>Proxy Type: </strong>' . $results['proxyType'] . '</p>';
echo '<p><strong>Is Proxy: </strong>' . $results['isProxy'] . '</p>';
}
```



# Reference

### Usage Type
Expand Down
156 changes: 146 additions & 10 deletions class.IP2Proxy.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?php

/*
* Copyright (C) 2005-2019 IP2Location.com
* Copyright (C) 2005-2020 IP2Location.com
* All Rights Reserved
*
* This library is free software: you can redistribute it and/or
Expand Down Expand Up @@ -31,7 +31,7 @@ class Database
*
* @var string
*/
public const VERSION = '2.1.0';
public const VERSION = '2.2.0';

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Error field constants ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
Expand Down Expand Up @@ -481,9 +481,9 @@ class Database
private $year;
private $month;
private $day;

// This variable will be used to hold the raw row of columns's positions
private $raw_positions_row;
private $raw_positions_row;

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Default fields //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Expand Down Expand Up @@ -858,13 +858,13 @@ protected function lookup($ip, $fields = null, $asNamed = true)
if ($fields === null) {
$fields = $this->defaultFields;
}

// Get the entire row based on the pointer value.
// The length of the row differs based on the IP version.
if (4 === $ipVersion) {
$this->raw_positions_row = $this->read($pointer - 1, $this->columnWidth[4] + 4);
} elseif (6 === $ipVersion) {
$this->raw_positions_row = $this->read($pointer - 1, $this->columnWidth[6]);
if ($ipVersion === 4) {
$this->raw_positions_row = $this->read($pointer - 1, $this->columnWidth[4] + 4);
} elseif ($ipVersion === 6) {
$this->raw_positions_row = $this->read($pointer - 1, $this->columnWidth[6]);
}

// turn fields into an array in case it wasn't already
Expand Down Expand Up @@ -1353,7 +1353,7 @@ private function read($pos, $len)
* @return string
*/
private function readString($pos, $additional = 0)
{
{
// Get the actual pointer to the string's head by extract from raw row data.
$spos = unpack('V', substr($this->raw_positions_row, $pos, 4))[1] + $additional;

Expand Down Expand Up @@ -1749,3 +1749,139 @@ private function binSearch($version, $ipNumber)
return false;
}
}

/**
* IP2Proxy web service class.
*/
class WebService
{
/**
* No cURL extension found.
*
* @var int
*/
public const EXCEPTION_NO_CURL = 10001;

/**
* Invalid API key format.
*
* @var int
*/
public const EXCEPTION_INVALID_API_KEY = 10002;

/**
* Web service error.
*
* @var int
*/
public const EXCEPTION_WEB_SERVICE_ERROR = 10003;

/**
* Constructor.
*
* @param string $apiKey API key of your IP2Proxy web service
* @param string $package Supported IP2Proxy package from PX1 to PX8
* @param bool $useSsl Enable or disabled HTTPS connection. HTTP is faster but less secure.
*
* @throws \Exception
*/
public function __construct($apiKey, $package = 'PX1', $useSsl = false)
{
if (!\extension_loaded('curl')) {
throw new \Exception(__CLASS__ . ": Please make sure your PHP setup has the 'curl' extension enabled.", self::EXCEPTION_NO_CURL);
}

if (!preg_match('/^[0-9A-Z]{10}$/', $apiKey) && $apiKey != 'demo') {
throw new \Exception(__CLASS__ . ': Please provide a valid IP2Proxy web service API key.', self::EXCEPTION_INVALID_API_KEY);
}

if (!preg_match('/^PX[0-9]+$/', $package)) {
$package = 'PX1';
}

$this->apiKey = $apiKey;
$this->package = $package;
$this->useSsl = $useSsl;
}

/**
* This function will look the given IP address up in IP2Proxy web service.
*
* @param string $ip IP address to look up
*
* @throws \Exception
*
* @return array|false
*/
public function lookup($ip)
{
$response = $this->httpRequest('http://api.ip2proxy.com/?' . http_build_query([
'key' => $this->apiKey,
'ip' => $ip,
'package' => $this->package,
]));

if (($data = json_decode($response, true)) === null) {
return false;
}

if ($data['response'] != 'OK') {
throw new \Exception(__CLASS__ . ': ' . $data['response'], self::EXCEPTION_WEB_SERVICE_ERROR);
}

return $data;
}

/**
* Get the remaing credit in your IP2Proxy web service account.
*
* @return int
*/
public function getCredit()
{
$response = $this->httpRequest('http://api.ip2proxy.com/?' . http_build_query([
'key' => $this->apiKey,
'check' => true,
]));

if (($data = json_decode($response, true)) === null) {
return 0;
}

if (!isset($data['response'])) {
return 0;
}

return $data['response'];
}

/**
* Open a remote web address.
*
* @param string $url Website URL
*
* @return bool|string
*/
private function httpRequest($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$response = curl_exec($ch);

if (!curl_errno($ch)) {
curl_close($ch);

return $response;
}

curl_close($ch);

return false;
}
}
12 changes: 11 additions & 1 deletion example.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php
require 'class.IP2Proxy.php';

// Lookup by local BIN database
$db = new \IP2Proxy\Database();
$db->open('./samples/IP2PROXY-IP-PROXYTYPE-COUNTRY-REGION-CITY-ISP-DOMAIN-USAGETYPE-ASN-LASTSEEN.SAMPLE.BIN', \IP2Proxy\Database::FILE_IO);

Expand Down Expand Up @@ -46,4 +47,13 @@
print_r($records);
echo '</pre>';

$db->close();
$db->close();

// Lookup by Web API
$ws = new \IP2Proxy\WebService('demo', 'PX8', false);

$results = $ws->lookup('1.0.241.135');

echo '<pre>';
print_r($results);
echo '</pre>';

0 comments on commit 2049b73

Please sign in to comment.