Extract Cookie Domain from URL β€” Don’t Hardcode It

Table of Contents

πŸ“– 1 minute read

Sending cookies to an API? Don’t hardcode the domain. Extract it from the URL instead.

The Problem

// ❌ Hardcoded domain β€” breaks when URL changes
$cookieJar->setCookie(new SetCookie([
    'Name' => 'session',
    'Value' => $token,
    'Domain' => 'api.example.com',
]));

Hardcoded domains break the moment someone changes the base URL in config, or you switch between staging and production environments.

The Fix

// βœ… Extract domain dynamically
$baseUrl = config('services.api.base_url');
$domain = parse_url($baseUrl, PHP_URL_HOST);

$cookieJar->setCookie(new SetCookie([
    'Name' => 'session',
    'Value' => $token,
    'Domain' => $domain,
]));

parse_url() with PHP_URL_HOST gives you just the hostname β€” no protocol, no path, no port. Clean and environment-agnostic.

Takeaway

Any time you need a domain, host, or path from a URL β€” use parse_url(). It handles edge cases (ports, trailing slashes, query strings) that string manipulation misses.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *