Integrate the Website Traffic API in PHP

November 12, 2026
Integrate the Website Traffic API in PHP

You need to decide where to show ads, which signups to enrich, or which domains to block—based on how much traffic a site gets and where that traffic comes from. By the end of this guide, you’ll call Klazify’s Website Traffic API from your stack, parse traffic signals like global rank, monthly visits, engagement, and top countries, and fit the response cleanly into a PHP-based workflow with caching and fallbacks.

Why Klazify is the right fit for website traffic analysis in your PHP stack

When you’re integrating traffic intelligence into PHP applications—such as ad placement review, partner vetting, or content filtering—you need accurate signals that pair cleanly with categorization. Klazify brings both together with one domain intelligence platform, so you can make decisions at ingest time without juggling multiple providers.

Illustration: Integrate the Website Traffic API in PHP
  • Accurate Website Categorization Using AI: Klazify analyzes full site content, enabling you to join traffic signals with precise IAB-mapped categories for filtering, enrichment, and brand safety gating.
  • Global Coverage: Inputs in many languages are supported, so global rankings and top-country traffic data make sense across international audiences.
  • Real-Time Classification: You’re not limited to stale lists—queries evaluate fresh content and recent domain signals you can trust for operational decisions.
  • Industry-Level Categories (IAB): Map traffic to IAB categories for ad-tech workflows, ensuring placements and segments respect industry standards.
  • Simple API Integration: A straightforward REST design means you can call it from PHP, queue it in workers, and cache results in Redis/MySQL with a few lines.
  • Compliance and Filtering: Combine category data with traffic sources and engagement to refine blocklists/allowlists or to escalate manual review.

If your scenario involves blocking risky categories, enriching signups in CRM, or auditing where ads run, tying traffic intelligence to categorization gives you a cohesive foundation for action in a PHP-based application.

What you’ll build: a traffic-aware domain decision in your pipeline

We’ll send a URL to the Website Traffic API, read the returned fields (global rank, monthly visits, engagement, traffic sources, and top countries), and convert them into a decision or enrichment step. You can run this behind a queue (e.g., for nightly audits) or in-line (with short timeouts) for immediate gating.

For category-level gating or brand safety, we’ll also show how to pair traffic intelligence with categorization using Klazify’s main endpoint. This way you can both assess volume/quality of traffic and map each domain to an IAB category for filtering or analytics downstream.

Endpoint and authentication

Traffic Intelligence Endpoint:

  • Method: POST
  • URL: https://www.klazify.com/api/domain_traffic_intelligence
  • Auth: Bearer token in the Authorization header
  • Body (JSON): {"url":"https://example.com"}

Notes:

  • Failed or unreachable calls are not billed.
  • Starter is $39.99/mo with a 7-day trial. You can create an account here: Register.
  • For full parameter and field descriptions, refer to the Documentation.

Quick start: cURL request

Here’s a copy-pasteable request you can run right now. It uses the Website Traffic API with a JSON body and Bearer token. Replace YOUR_API_KEY with your key.

curl -X POST "https://www.klazify.com/api/domain_traffic_intelligence" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url":"https://cbsnews.com"}'

Response includes fields such as global_rank, country_rank, category_rank, monthly_visits, engagement, traffic_sources, and top_countries. Use them to drive allow/deny decisions, enrich CRM records, or prioritize manual review.

JavaScript example: parse traffic and act

The snippet below calls the same endpoint and illustrates how you might parse and use the returned fields in a Node.js or serverless function. You can port this logic to PHP easily (see the PHP request sketch further below).

import fetch from "node-fetch";

const API_URL = "https://www.klazify.com/api/domain_traffic_intelligence";
const API_KEY = process.env.KLAZIFY_API_KEY; // Set securely

async function fetchTrafficIntelligence(targetUrl) {
  const res = await fetch(API_URL, {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${API_KEY}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ url: targetUrl })
  });

  if (!res.ok) {
    // 4xx/5xx are not billed if the call fails or is unreachable
    const text = await res.text();
    throw new Error(`Traffic API error: ${res.status} - ${text}`);
  }

  const json = await res.json();
  return json;
}

function toDecision(traffic) {
  // Example policy:
  // - Require global_rank and monthly_visits to exist
  // - Prefer higher engagement (e.g., pages_per_visit or avg_visit_duration)
  // - Consider top_countries if you have regional policies
  const {
    global_rank,
    country_rank,
    category_rank,
    monthly_visits,
    engagement,
    traffic_sources,
    top_countries
  } = traffic || {};

  // Basic null checks
  if (!global_rank || !monthly_visits) {
    return { action: "review", reason: "insufficient_traffic_data" };
  }

  // Illustrative thresholds/policies. Keep them configurable.
  const hasMeaningfulVisits = monthly_visits && monthly_visits.total > 0;
  const hasEngagement = engagement && (
    engagement.pages_per_visit ||
    engagement.avg_visit_duration ||
    engagement.bounce_rate !== undefined
  );

  // Simple decision tree
  if (!hasMeaningfulVisits) {
    return { action: "deny", reason: "no_visits" };
  }
  if (!hasEngagement) {
    return { action: "review", reason: "no_engagement_metrics" };
  }

  // Example: if direct or search traffic sources dominate, we might trust it more
  const majorSources = traffic_sources ? Object.entries(traffic_sources)
    .filter(([, v]) => typeof v === "number")
    .sort((a, b) => b[1] - a[1])
    .slice(0, 2)
    .map(([k]) => k) : [];

  return {
    action: "allow",
    reason: "meets_traffic_criteria",
    summary: {
      global_rank,
      country_rank,
      category_rank,
      monthly_visits,
      engagement,
      majorSources,
      topCountries: top_countries
    }
  };
}

// Example usage
(async () => {
  try {
    const traffic = await fetchTrafficIntelligence("https://example.org");
    const decision = toDecision(traffic);
    console.log(JSON.stringify(decision, null, 2));
  } catch (err) {
    console.error(err);
  }
})();

Production tip: cache the traffic response per domain (e.g., Redis for 24 hours) to avoid redundant API calls during bursts or re-ingestion. For unknown/new domains, return a temporary “review” state and schedule a retry.

Optional PHP request sketch

If you prefer to perform the call from PHP, this cURL-based snippet shows the structure. The parsing and policy logic can mirror the JavaScript above.

<?php
$apiKey = getenv('KLAZIFY_API_KEY');
$payload = json_encode([ 'url' => 'https://example.org' ]);

$ch = curl_init('https://www.klazify.com/api/domain_traffic_intelligence');
curl_setopt_array($ch, [
  CURLOPT_POST => true,
  CURLOPT_HTTPHEADER => [
    'Authorization: Bearer ' . $apiKey,
    'Content-Type: application/json'
  ],
  CURLOPT_POSTFIELDS => $payload,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 10
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($response === false || $httpCode >= 400) {
  // Not billed if unreachable/failed; handle gracefully and retry later
  error_log('Traffic API error: ' . curl_error($ch) . ' status=' . $httpCode);
  curl_close($ch);
  http_response_code(202);
  exit;
}

curl_close($ch);
$data = json_decode($response, true);
// TODO: Apply your allow/review/deny rules to $data
echo json_encode([ 'ok' => true, 'traffic' => $data ]);

How to use the returned fields

When the traffic endpoint returns data, you’ll typically read these fields:

  • global_rank: A comparative ranking metric across the global web. Use it to gauge overall prominence.
  • country_rank: Rank scoped to a specific country. Useful for geo-targeted campaigns or compliance.
  • category_rank: Rank within an industry/category. Combine this with your targeting lists or IAB mapping.
  • monthly_visits: Total visits and breakdowns you can apply for thresholds and ROI modeling.
  • engagement: Metrics such as pages per visit, average duration, and bounce rate to qualify visit quality.
  • traffic_sources: Proportions from direct, search, social, referrals, etc., to help flag anomalies.
  • top_countries: Where users come from. Useful for regional filters and localization planning.

Actionable mapping to your workflow

  • Blocklists/Allowlists: If monthly_visits is low or engagement is thin, route to review; otherwise allow.
  • Ad Audits: Check top_countries and category_rank to confirm placements are aligned with targeting.
  • CRM Enrichment: Store global_rank and monthly_visits alongside firmographic data for lead scoring.
  • Security: Use traffic_sources anomalies to queue domains for additional scrutiny.

Pairing traffic with categorization (IAB taxonomy)

For many pipelines, traffic metrics are only half the story. You’ll often need an IAB-mapped category to enforce brand safety rules or to tag content in your analytics warehouse. You can get this via the main categorization endpoint:

  • Endpoint: https://www.klazify.com/api/categorize
  • Purpose: Website classification and content categorization

Official example response (use these exact values):


{
    "domain": {
        "categories": [
            {
                "confidence": 0.92,
                "name": "/Computers & Electronics/Consumer Electronics",
                "IAB-632-596": "Consumer Electronics/Technology & Computing/Consumer Electronics"
            },
            {
                "confidence": 0.89,
                "name": "/Internet & Telecom/Mobile & Wireless/Mobile Phones"
            }
        ],
        "social_media": null,
        "logo_url": "https://klazify.s3.amazonaws.com/2110787991611585019600ed5fb1d1300.04730104.png"
    },
    "success": true,
    "objects": {
        "company": {
            "url": "https://www.apple.com/",
            "name": "Apple",
            "city": "Cupertino",
            "stateCode": "CA",
            "countryCode": "US",
            "employeesRange": "100K+",
            "revenue": 274515000000,
            "raised": null,
            "tags": [
                "E-commerce",
                "Consumer Electronics",
                "Mobile",
                "B2C"
            ],
            "tech": [
                "omniture_adobe_analytics",
                "atlassian_confluence",
                "successfactors",
                "apache_apex",
                "talend",
                "oracle_peoplesoft",
                "salesforce",
                "stripe",
                "dell_boomi_atomsphere",
                "gigya",
                "sage_50cloud",
                "quickbooks",
                "webmethods",
                "apache_tomcat",
                "alteryx",
                "tibco_rendezvous",
                "atlassian_jira",
                "..."
            ]
        }
    },
    "domain_registration_data": {
        "domain_age_date": "1987-02-19",
        "domain_age_days_ago": "13026",
        "domain_expiration_date": "2030-02-20",
        "domain_expiration_days_left": "123"
    },
    "similar_domains": [
        "bestbuy.com",
        "icloud.com",
        "microsoft.com",
        "macrumors.com",
        "google.com",
        "samsung.com",
        "twitter.com",
        "hp.com",
        "bhphotovideo.com",
        "dell.com"
    ]
}

How to use these fields:

  • domain.categories: Map to IAB codes for brand safety, ad targeting, or content filtering. Confidence can guide manual review vs. auto-approve.
  • domain.logo_url: Enrich UI, CRM records, or admin consoles with a recognizable logo.
  • objects.company: Pull company name, location, employeesRange, revenue, tags, and tech for lead enrichment or vendor vetting.
  • domain_registration_data: Use domain age and expiration windows in risk scoring (e.g., very young domains = higher review flag).
  • similar_domains: Expand research, detect clusters, or augment competitive sets.

By combining traffic intelligence with categorization, your PHP pipeline can filter by IAB category and then scale decisions using traffic quality and volume.

Which fields should drive which decision?

Field What it tells you Common actions Notes
global_rank Overall prominence across the web Set minimum thresholds to auto-allow or escalate to review Cache per domain; avoid re-checking frequently
country_rank Prominence within a country Trigger region-specific policies, compliance checks Use in geo-targeted campaigns
category_rank Position within its industry/category Refine industry segments; prioritize partnerships Pair with IAB mapping from categorization
monthly_visits Estimated volume of visits Set traffic floor for ad placements or affiliate approvals Use rolling cache; revisit periodically
engagement Quality of visits (e.g., pages per visit, duration) Flag thin engagement for manual review or lower bid Tune thresholds per vertical
traffic_sources Distribution by source (direct, search, social, referrals) Detect anomalies (e.g., suspicious spikes) Combine with fraud/risk signals
top_countries Geographic distribution of traffic Enforce geo policies; localize content Match against your target markets

Operational guidance: batching, caching, and fallbacks

  • Batching: If you ingest large lists of domains, push them into a queue (e.g., SQS, RabbitMQ) and call the API concurrently with a capped worker pool. Keep per-worker concurrency reasonable to respect rate policies in the Documentation.
  • Caching: Cache responses per domain for at least several hours. A Redis TTL of 12–24 hours is common for traffic signals; categorization can often be cached longer.
  • Retries: If a call times out or the host is unreachable, retry with exponential backoff. Unreachable/failed calls are not billed.
  • Handling unknown/new domains: If critical fields are missing (e.g., global_rank or monthly_visits), assign a “review” state and schedule a retry. Log the occurrence for visibility.
  • Timeouts: Use short client timeouts (5–10 seconds) for synchronous flows. Queue long-running evaluations.
  • Schema stability: Store raw JSON in your data lake alongside normalized fields so you can re-parse if your policy evolves.

Mapping categories to your taxonomy

Many teams keep an internal taxonomy in addition to IAB. A reliable approach is to maintain a mapping table keyed by Klazify category names or IAB codes. On ingest:

  • Read domain.categories and any IAB fields.
  • Normalize to your internal categories using your mapping table.
  • If there’s no direct mapping or confidence is below your threshold, route for review but still store the raw category string and confidence.

This hybrid approach retains fidelity to the IAB standard while preserving your internal business definitions.

Putting it all together in your PHP pipeline

Example flow

  1. Receive a new partner domain in a PHP controller.
  2. Check cache. If miss, enqueue domain for traffic fetch and (optionally) categorization fetch.
  3. Workers call:
    • POST https://www.klazify.com/api/domain_traffic_intelligence with the domain URL.
    • Optionally call https://www.klazify.com/api/categorize for IAB mapping.
  4. Persist raw JSON and normalized fields: global_rank, monthly_visits, engagement stats, traffic_sources, top_countries, and categories.
  5. Run your decision policy. If fields are missing or below thresholds, set status=review.
  6. Expose a review dashboard that shows:
    • Traffic summary and engagement.
    • IAB category and confidence.
    • Company name/logo for quick recognition.
    • Top countries and dominant traffic sources.

Compliance and governance note

When you act on traffic signals (allow/deny/review), log: request timestamp (UTC), domain, response snapshot, and the decision with rules that fired. This audit trail helps explain why a domain was blocked or approved and is useful for both ad ops and compliance teams.

Monitoring and alerting

  • Set alerts for error rates, timeouts, and spikes in unreachable domains.
  • Track distribution of decisions (allow/review/deny) over time to tune thresholds.
  • Sample a percentage of “allow” decisions for manual QA.

Access, pricing, and next steps

  • Starter plan is $39.99/mo and includes a 7-day trial to get started quickly.
  • Create your account here: Register.
  • Review API details and fields: Documentation.
  • If you manage multiple projects or teams, visit the MCP page.

FAQ

Does the Website Traffic API support batching multiple domains in one request?
Send one domain per request. For large lists, push domains into a queue and run concurrent workers with a cap. Cache results to minimize repeated lookups.

What happens if a request fails or the target site is unreachable?
Failed or unreachable calls are not billed. Implement retries with exponential backoff and place the domain in a temporary “review” state until a successful fetch.

How often should I refresh traffic data?
It depends on your use case. Many teams refresh every 12–24 hours for operational decisions. Use a TTL in Redis or your database to invalidate cached entries on your schedule.

Can I use IAB categories with my own internal taxonomy?
Yes. Keep a mapping table from Klazify’s category names or IAB codes to your internal labels. Apply it during ingestion, and keep the original category plus confidence for transparency.

Can I enrich CRM records with company details and logo?
Yes. Use the categorization endpoint to retrieve company information and logo_url. Store them alongside traffic fields to enhance lead scoring and account research.

Ready to integrate traffic intelligence and categorization into your PHP workflow? Create your free trial account and start testing today: Register. For endpoint details and field definitions, see the Documentation.

Ready to use Klazify?

Start classifying websites, enriching company data, and exploring web intelligence.

Get Started Free