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.

Leave a Reply