Integrate the Domain Expiration API in PHP

November 18, 2026
Integrate the Domain Expiration API in PHP

Your team needs to catch domains before they expire, block signups from throwaway websites, and alert account owners when their parked or lapsed domains put traffic and deliverability at risk. By the end of this guide, you will have a working PHP integration that checks a domain’s age and expiration, plugs those values into your pipeline, and enforces actions such as preventing new users from registering with near-expired domains or flagging risky leads for review.

Why Klazify fits domain expiration monitoring in production

When you manage thousands or millions of domains across ad placements, CRM signups, partner vetting, or cybersecurity controls, you need a single API that returns expiration timelines reliably and at low latency. Klazify’s domain intelligence stack gives you consistent signals you can automate around, including domain age and expiration dates you can compute against in real time.

Illustration: Integrate the Domain Expiration API in PHP
  • Accurate website categorization using AI: If you also need to block by content or enrich leads, Klazify analyzes full website content (not just metadata). This is useful when combining expiration checks with content policies in one pass.
  • Global coverage: You’ll encounter domains in multiple languages and TLDs. Klazify’s models operate globally, which helps when expiration enforcement runs across international sites.
  • Real-time analysis: Expiration policies need up-to-date signals. Klazify refreshes data rather than relying on stale datasets, so your enforcement is timely.
  • Industry-level categories via IAB taxonomy: If a domain is active but misaligned with your brand safety policy, you can pair expiration status with IAB-mapped categories to decide whether to proceed, enrich, or block.
  • Simple API integration: A straightforward POST request with a JSON body means you can drop the check into PHP middleware, message workers, or serverless functions without heavy dependencies.
  • Compliance and filtering: Combine expiration thresholds (e.g., block if fewer than N days remain) with category-based allowlists or blocklists for a single, consistent gate at signup, ad-serving, or data ingestion time.

You can explore the platform at https://www.klazify.com and then create a free account to test your integration.

When to check domain expiration in your pipeline

  • Signup and onboarding: Reject or flag users whose email domains have fewer than 14 days left, or whose domains are newly registered and therefore risky.
  • CRM and lead enrichment: Score leads lower when the company domain is close to expiration; route them to manual review if needed.
  • Ad tech and brand safety: Audit where ads will run and pause placements on domains nearing expiration to avoid wasted impressions on lapsed sites.
  • Cybersecurity and analytics: Detect disposable or newly minted domains to reduce phishing risk and data noise.

The endpoint you’ll call

Use the following endpoint to retrieve a domain’s age and expiration:

  • HTTP method: POST
  • URL: https://www.klazify.com/api/domain_expiration
  • Authentication: Bearer token in the Authorization header
  • Body: JSON with a URL string

Request body:

{
  "url": "https://cbsnews.com"
}

Response fields you will consume in code:

  • domain_age_date: The date the domain was first registered (YYYY-MM-DD).
  • domain_age_days_ago: How many days ago the domain was registered (stringified integer).
  • domain_expiration_date: When the domain is scheduled to expire (YYYY-MM-DD).
  • domain_expiration_days_left: How many days remain until expiration (stringified integer).

Copy-paste cURL request

Run this from your terminal to validate end-to-end connectivity. Replace YOUR_API_KEY with your token.

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

Failed or unreachable calls are not billed, which makes iterative testing simpler.

Official JSON example you’ll map to

The following is an example response format from Klazify that also demonstrates where domain registration data appears in the object. You will read the values from domain_registration_data in your code.


{
    "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 it:

  • domain_age_date and domain_age_days_ago help you identify newly registered domains for risk scoring.
  • domain_expiration_date and domain_expiration_days_left power your enforcement logic (e.g., block if days_left < 7).
  • If you also call categorization, categories and IAB mappings allow you to apply content-based policies alongside expiration thresholds.

Implement the check in PHP

The snippet below shows how to call the endpoint from PHP, parse the JSON, and act on a simple policy: reject a domain if it expires within 7 days or if the domain is younger than 14 days.

<?php
$apiKey = 'YOUR_API_KEY';
$endpoint = 'https://www.klazify.com/api/domain_expiration';

$payload = json_encode([
  'url' => 'https://example.com'
]);

$ch = curl_init($endpoint);
curl_setopt_array($ch, [
  CURLOPT_POST => true,
  CURLOPT_HTTPHEADER => [
    'Authorization: Bearer ' . $apiKey,
    'Content-Type: application/json'
  ],
  CURLOPT_POSTFIELDS => $payload,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 15
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErr = curl_error($ch);
curl_close($ch);

if ($curlErr) {
  // Network or TLS error: do not billable per docs; treat as soft-fail and retry later
  error_log('Klazify call failed: ' . $curlErr);
  http_response_code(202);
  exit;
}

if ($httpCode < 200 || $httpCode >= 300) {
  // Non-2xx API response: handle gracefully
  error_log('Klazify non-2xx: ' . $httpCode . ' ' . $response);
  http_response_code(202);
  exit;
}

$data = json_decode($response, true);

$reg = $data['domain_registration_data'] ?? null;
if (!$reg) {
  // Unknown or unparsable domain: fallback policy (e.g., flag for review)
  http_response_code(200);
  echo json_encode(['status' => 'review', 'reason' => 'no_registration_data']);
  exit;
}

// Note: numeric values are strings; cast safely
$daysOld = isset($reg['domain_age_days_ago']) ? (int)$reg['domain_age_days_ago'] : null;
$daysLeft = isset($reg['domain_expiration_days_left']) ? (int)$reg['domain_expiration_days_left'] : null;

$policy = [
  'min_age_days' => 14,  // require at least 14 days since registration
  'min_days_left' => 7   // require at least 7 days until expiration
];

$decision = 'allow';
$reasons = [];

if ($daysOld !== null && $daysOld < $policy['min_age_days']) {
  $decision = 'review';
  $reasons[] = 'young_domain';
}

if ($daysLeft !== null && $daysLeft <= $policy['min_days_left']) {
  $decision = 'block';
  $reasons[] = 'near_expiration';
}

$result = [
  'decision' => $decision,
  'reasons' => $reasons,
  'domain_age_date' => $reg['domain_age_date'] ?? null,
  'domain_expiration_date' => $reg['domain_expiration_date'] ?? null,
  'domain_age_days_ago' => $daysOld,
  'domain_expiration_days_left' => $daysLeft
];

header('Content-Type: application/json');
echo json_encode($result);

Drop this into a middleware layer for signups, or run it as a worker that enriches CRM records. Cache successful lookups per domain to avoid repetitive calls under load.

JavaScript example for CI or serverless checks

If you prefer Node.js for scheduled audits or serverless webhooks, the following fetch-based example calls the same endpoint, then throws if the domain is expiring in 3 days or fewer.

import fetch from 'node-fetch';

const API_KEY = 'YOUR_API_KEY';
const urlToCheck = 'https://example.com';

async function getDomainExpiration(url) {
  const res = await fetch('https://www.klazify.com/api/domain_expiration', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ url })
  });

  if (!res.ok) {
    const text = await res.text();
    throw new Error(`Klazify error: ${res.status} ${text}`);
  }

  const json = await res.json();
  const reg = json.domain_registration_data || {};
  const daysLeft = Number(reg.domain_expiration_days_left);
  const ageDays = Number(reg.domain_age_days_ago);

  return {
    daysLeft,
    ageDays,
    ageDate: reg.domain_age_date,
    expirationDate: reg.domain_expiration_date
  };
}

(async () => {
  const { daysLeft, expirationDate } = await getDomainExpiration(urlToCheck);

  if (Number.isFinite(daysLeft) && daysLeft <= 3) {
    throw new Error(`Block: domain expires in ${daysLeft} days on ${expirationDate}`);
  }

  console.log('OK to proceed', { daysLeft, expirationDate });
})();

Map expiration data into actions

Signal Typical threshold Action in pipeline Notes
domain_expiration_days_left <= 3 Block Prevents short-lived or lapsed domains from entering your system.
domain_expiration_days_left 4–14 Flag for review Notify account owner or pause ad spend on the domain.
domain_age_days_ago < 14 Lower confidence/score Newly registered domains are more likely to be disposable.
domain_age_date N/A Audit/forensics Use for reports or to justify an allow/deny decision historically.

Combining expiration with categorization

If you also need category-based filtering, you can call Klazify’s categorization endpoint to obtain IAB-mapped categories alongside registration data. This lets you, for example, approve only domains with sufficient days left and that match your allowlist categories.

  • Use categories.name and, when present, the IAB mapping to translate to your internal content policy.
  • Keep a small in-memory or database mapping from Klazify category paths to your policy labels (e.g., “Allowed,” “Restricted,” “Block”).
  • Apply expiration rules first to eliminate risky domains early, then apply category-based controls to the survivors.

Refer to the Documentation for full details about the categorization endpoint and fields. You can also explore the platform capabilities at https://www.klazify.com.

Operational guidance: batching, caching, retries

  • Batching: Issue requests in parallel at a controlled concurrency that matches your worker capacity. If you process large lists, queue domains and throttle to maintain consistent latency.
  • Caching: Cache the result per domain. For expiration data, a 24-hour cache is common; shorten it if you require tighter freshness for critical workflows.
  • Unknown or new domains: If domain_registration_data is missing, mark the record for review and retry later. Don’t silently pass unknowns as “safe.”
  • Retries: Network or transient HTTP errors should be retried with exponential backoff. Failed or unreachable calls are not billed.
  • Rate limits: Design for backoff on non-2xx responses and distribute calls over time. Consult the MCP and documentation for guidance on operational constraints.
  • Logging: Record request IDs, HTTP status, and parsed fields (days_left, age_days) for auditability. Redact API keys from logs.

Data modeling tips for pipelines

  • Schema: Store normalized fields: domain (string), age_date (date), age_days (int), expiration_date (date), expiration_days_left (int), last_checked_at (timestamp).
  • Idempotency: If you enrich the same domain in multiple places, write a single source of truth table keyed by domain and reuse cached results.
  • Eventing: Emit events when expiration_days_left crosses thresholds (e.g., 14→13, 7→6, 3→2) to trigger notifications or automated blocks.
  • Testing: Seed fixtures with domains representing each branch: newly registered, long-lived, expiring soon, expired, and unknown.

Handling category mapping to your taxonomy

Many teams already maintain internal policy tags. If you also use Klazify’s categorization fields, map Klazify’s category paths to your policy once and reuse the mapping everywhere.

  • Create a policy table that links Klazify category names to your labels (e.g., “Allowed,” “NeedsReview,” “Blocked”).
  • On ingestion, resolve the category path to a policy label and store it next to the expiration fields.
  • When categories are absent or null, default to “NeedsReview” and do not block solely due to missing category data unless your policy mandates it.

Rollout plan and guardrails

  • Shadow mode: Start by logging decisions without enforcing them. Compare outcomes against your support tickets and fraud signals.
  • Progressive enforcement: Enforce the strictest rule for very short windows (e.g., days_left ≤ 3), and flag—but do not block—higher thresholds initially.
  • Overrides: Provide an admin override list for legitimate edge cases where near-expiration domains are known and approved.
  • Monitoring: Create dashboards for error rates, average latency, cache hit rate, and decision counts (allow/review/block).

Cost and getting access

The Starter plan is $39.99/mo with a 7-day trial. You can test freely and build your integration—failed or unreachable calls are not billed. Create your account here: Register.

End-to-end checklist

  • Make a POST call to /api/domain_expiration with the URL in the body.
  • Parse domain_age_date, domain_age_days_ago, domain_expiration_date, domain_expiration_days_left.
  • Apply thresholds and return an allow/review/block decision.
  • Cache results per domain and schedule periodic refreshes.
  • Optionally call categorization to add IAB-mapped categories for policy-based gating.
  • Alert on threshold crossings and provide admin overrides.

FAQ

How often should I refresh expiration data?
For most pipelines, daily is sufficient. If you run time-sensitive ad or security workflows, consider refreshing high-risk or high-value domains more frequently.

What if the API can’t reach a domain or returns no registration data?
Treat it as “NeedsReview,” retry with backoff, and avoid auto-approving unknowns. Since failed or unreachable calls are not billed, retrial strategies are safe to implement.

Are the number fields returned as strings?
Yes, cast domain_age_days_ago and domain_expiration_days_left to integers before comparing to thresholds.

Can I combine expiration checks with content filtering?
Yes. Use the categorization endpoint to get categories and IAB mappings, then enforce both content and expiration rules in a single policy decision.

How do I handle burst traffic?
Use a work queue, cache successful lookups per domain, and throttle concurrency. Log non-2xx responses and back off automatically.

Ready to add reliable expiration checks to your PHP stack? Create a free account and start integrating today: Register. For implementation details and additional endpoints, see the Documentation.

Ready to use Klazify?

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

Get Started Free