IP Lookup in PHP: City, ASN, and Cloud Flag
You need to look up an IP from PHP and immediately know the city, the network (ASN), and whether the address is coming from a cloud provider or a VPN. By the end of this walkthrough, you’ll call ipXapi from PHP using a Bearer token, read the JSON you care about (city, ASN, is_cloud_provider, is_vpn), branch your application logic on those values, and ship a production-ready integration.
What you’ll build and the data you’ll use
You’ll send a Bearer-authenticated GET to the ipXapi IP lookup endpoint from PHP and parse the JSON response. For a concrete test, you’ll look up the official sample address 148.105.12.120 (MailChimp / AS14782, Mountain View) and inspect the security flags (is_cloud_provider=true, is_vpn=false). Those flags are central when you need to treat cloud-sourced or VPN traffic differently.
If you’re just getting started, there’s a 7-day trial (or 50 requests, whichever comes first). After that, Basic is $29.99/mo. You can create your key here: Register.
Endpoint, method, and auth
The IP Lookup is an HTTP GET. There is no form post. You’ll call:
GET https://ipxapi.com/api/ip?ip=
Authentication is a Bearer token that you place in the Authorization header. Replace YOUR_API_KEY with a key from your ipXapi dashboard.
curl -sS \
-H "Authorization: Bearer YOUR_API_KEY" \
"https://ipxapi.com/api/ip?ip=148.105.12.120"
Tip: keep the IP address parameter explicit (ip=...). If you need to make multiple decisions off the same IP, cache the parsed result for a short period that suits your use case to reduce round-trips.
PHP example: GET the IP’s city, ASN, and cloud/VPN flags
The following is the official PHP snippet showing how to call ipXapi from PHP for the official MailChimp test IP. It uses Bearer authentication and reads the key security flags you’ll typically branch on in your application.
$ch = curl_init('https://ipxapi.com/api/ip?ip=148.105.12.120');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Accept: application/json',
'Authorization: Bearer YOUR_KEY',
],
]);
$json = json_decode(curl_exec($ch), true);
$city = $json['city'] ?? null;
$cloud = $json['security']['is_cloud_provider'] ?? null;
How to read the JSON response
The API returns JSON. The official security object is shown below; you’ll branch on its fields in your code.
{
"status": "success",
"isp": "MailChimp",
"org": "MailChimp",
"as": "AS14782 MailChimp",
"query": "148.105.12.120",
"city": "Mountain View",
"security": {
"is_proxy": false,
"is_tor": false,
"is_cloud_provider": true,
"is_vpn": false,
"is_anonymous": false,
"is_threat": false
}
}
What to look for:
- is_cloud_provider: boolean. True if the IP belongs to known cloud infrastructure. Useful for gating trials, flagging automated traffic, or routing traffic to extra verification.
- is_vpn: boolean. True if the address is identified as coming through a VPN. Use it to step up authentication or adjust rate limiting.
Beyond security, the same response includes geolocation and network details for the IP address. For the official sample 148.105.12.120 you should expect city-level data (Mountain View) and the autonomous system (AS14782, MailChimp). Read those fields in your code if you need city-based personalization or ASN-based rules.
Always expect that specific fields may be absent for some IPs. When a field you rely on is missing, use a safe default in your application (for example, treat unknown as not cloud and not VPN, or require a fallback verification step).
Error handling, success checks, and missing values
Production code should handle:
- HTTP errors: Check the HTTP status code. Retry transient network failures with backoff rather than hammering the endpoint.
- Explicit failure flags: If the response payload includes a boolean success or error information, branch on that before accessing properties. When you see success=false (or an error field), log it, surface a safe message upstream, and avoid assuming any fields exist.
- Missing properties: Treat unknown or empty fields conservatively. For booleans like is_cloud_provider or is_vpn, use a default path in your logic if the fields are absent.
Serialization and types: Booleans arrive as JSON true/false; textual attributes like city and ASN are strings. Parse as UTF-8. Timestamps (if included in your plan or response) are provided as strings; treat them as opaque unless you need them, and normalize to your server timezone before comparison.
Caching: Cache results by IP for a window that fits your use case (e.g., per session). Many IP attributes do not change minute-to-minute, and caching will reduce latency and API usage.
Reading ASN, city, and cloud/VPN from JavaScript
Here is a minimal Node.js/JavaScript example using fetch. It calls the same endpoint, reads the cloud and VPN booleans from the security object, and logs the city and ASN if present. Adjust field access to match your application’s needs.
import fetch from "node-fetch";
const API_KEY = process.env.IPXAPI_KEY || "YOUR_API_KEY";
const IP = "148.105.12.120"; // Official sample (MailChimp / AS14782, Mountain View)
async function run() {
const url = `https://ipxapi.com/api/ip?ip=${encodeURIComponent(IP)}`;
const res = await fetch(url, {
headers: { Authorization: `Bearer ${API_KEY}` }
});
if (!res.ok) {
console.error("HTTP error:", res.status, await res.text());
return;
}
const data = await res.json();
// Security flags
const isCloud = data?.security?.is_cloud_provider === true;
const isVpn = data?.security?.is_vpn === true;
// Optional details (may be absent depending on the IP and plan)
const city = data?.city || null;
const asn = data?.asn || data?.as || null; // Read whichever field is provided
console.log({ ip: IP, city, asn, isCloud, isVpn });
// Example branching
if (isCloud || isVpn) {
// Step up auth, show captcha, or apply rate limits
} else {
// Normal flow
}
}
run().catch(err => {
console.error("Request failed:", err);
});
Go-live checklist
Set up your credentials
- Register for your API key: Register — 7-day trial.
- Copy your Bearer key from the dashboard.
Integrate the request
- Use GET https://ipxapi.com/api/ip?ip= from PHP (Bearer auth).
- Parse the JSON and branch on the security flags.
When testing, use the official MailChimp IP 148.105.12.120. In production, pass the client IP gathered by your application (considering proxies and load balancers where applicable).
When to use city, ASN, and cloud/VPN in your app
Practical uses include:
- City: Content localization, language defaults, or routing to the nearest PoP. If city is missing, fall back to country- or region-level behavior.
- ASN: Block or allow lists by network operator, traffic-shaping decisions, or fraud heuristics (e.g., new-account creation from specific ASNs).
- Cloud/VPN: Step up authentication, reduce free-tier quotas, or require extra verification for signups from known cloud/VPN ranges.
Keep your rules simple and observable. Log the IP, flags, and decision taken so you can later audit and tune thresholds without guessing.
Management, MCP, and documentation
For account management and platform-level details, check the MCP: MCP. For parameter and field reference, consult the Documentation. If you need advanced fields beyond what’s shown here, you’ll find them there along with plan-specific notes.
Operational tips
- Idempotency: The same IP will return the same attributes for a period; cache responses to reduce load and improve user-facing latency.
- Timeouts: Set a reasonable HTTP timeout in your PHP client. On timeout, continue with a safe default branch (e.g., treat as normal traffic) and log for later retry.
- Privacy: Only store what you need. If you persist IP lookups, define a retention period and mask or hash IPs if policy requires.
FAQ
How do I authenticate requests from PHP?
Use an Authorization header with a Bearer token: Authorization: Bearer YOUR_API_KEY. Do not send the key as a query parameter.
What if the API returns an error or success=false?
Check the HTTP status and look for an error or success field in the JSON. If you detect a failure, avoid dereferencing fields, log details, and apply a safe default in your app’s flow.
Which fields should I branch on for risk controls?
Start with security.is_cloud_provider and security.is_vpn. Then refine with city and ASN for location- or network-aware policies.
Can I test without deploying to production?
Yes. Use the official IP 148.105.12.120 in development and staging. It represents MailChimp (AS14782) in Mountain View with is_cloud_provider=true and is_vpn=false, so you can test both allow and step-up paths.
Is there a free option to try this?
Yes, you get a 7-day trial or 50 requests. After that, Basic is $29.99/mo.
Ready to wire IP intelligence into your PHP app? Start your 7‑day trial, grab your Bearer key, and ship your first lookup in minutes: Register.
