Artikel

Verwendung des API

Unten sind die Quelltexte in PHP und Python(für Django) für den Zugriff auf die Datenbank über API vorgestellt. Bald werden andere Programmiersprachen verfügbar sein.

PHP und fsockopen

// Ihre Domainname
$site_name = "www.your-site-name.com";

function getUserCountry() {
    $fp = fsockopen("api.wipmania.com", 80, $errno, $errstr, 5);
    if (!$fp) {
        // API is currently down, return as "Unknown" :(
        return "XX";
    } else {
        $out = "GET /".$_SERVER['REMOTE_ADDR']."?".$site_name." HTTP/1.1\r\n";
        $out .= "Host: api.wipmania.com\r\n";
        $out .= "Typ: php\r\n";
        $out .= "Ver: 1.0\r\n";
        $out .= "Connection: Close\r\n\r\n";
        fwrite($fp, $out);
        while (!feof($fp)) {
            $country = fgets($fp, 3);
        }
        fclose($fp);
        return $country;
    }
}

PHP und curl

Andere Alternative (Danke an www.anieto2k.com)
// Ihre Domainname
$site_name = "www.your-site-name.com";

function getUserCountry() {
    $url = 'http://api.wipmania.com/'.$_SERVER['REMOTE_ADDR'].'?'.$site_name;
    $ch = curl_init();
    $headers = "Typ: phpcurl\r\n";
    $headers .= "Ver: 1.0\r\n";
    $headers .= "Connection: Close\r\n\r\n";
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array($headers));
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}

Für framework Django (Python)

In Ihrem views:
from worldip import getUserCountry
remote_addr = request.META.get('REMOTE_ADDR',"127.0.0.1")
country = getUserCountry(remote_addr)
Fügen Sie ein in settings.py Ihr URL als SITE_URL, wie
SITE_URL = "http://www.google.com"
Kleine Funktion getUserCountry in worldip.py, hier ist sie herunterzuladen
#!/usr/bin/env python

from urllib2 import urlopen, Request
import re, socket
from django.conf import settings

domain_re = re.compile('^(http|https):\/\/?([^\/]+)')
domain = domain_re.match(settings.SITE_URL).group(2)

def getUserCountry(ip):
    url = "http://api.wipmania.com/" + ip + "?" + domain
    socket.setdefaulttimeout(5)
    headers = {'Typ':'django','Ver':'1.0','Connection':'Close'}
    try:
        req = Request(url, None, headers)
        urlfile = urlopen(req)
        land = urlfile.read()
        urlfile.close()
        return land[:2]
    except Exception:
        return "XX"
Falls Sie unsere Datenbank oder API verwenden, würden wir uns sehr über die entsprechende Link auf die WIPmania-Seite freuen!
Tags: , , ,