-
Notifications
You must be signed in to change notification settings - Fork 309
Open
Description
Curl/libcurl use the netscape cookie format, CURLOPT_COOKIEFILE/CURLOPT_COOKIEJAR both use the netscape format, and if you search for "cookie export" on addons.mozilla.org or chromewebstore.google.com , the majority of addons export to the netscape format, or support multiple formats (with netscape being ubiquitous)
Can we get a Netscape cookie import method?
Here is my attempt, seems to be working:
function importNetscapeCookies(string $rawCookies, \HeadlessChromium\Page $page): void
{
$cookies = [];
foreach (preg_split("/\r?\n/", $rawCookies) as $line) {
$line = trim($line);
if ($line === '') {
continue;
}
$httpOnly = false;
// Handle Netscape cookies with HttpOnly prefix: "#HttpOnly_"
if (str_starts_with($line, '#HttpOnly_')) {
$httpOnly = true;
$line = substr($line, 10); // strip prefix
} elseif ($line[0] === '#') {
// Comment line, skip
continue;
}
// Split by tabs if present; otherwise fallback to any whitespace
$parts = strpos($line, "\t") !== false
? explode("\t", $line)
: preg_split('/\s+/', $line);
if (!is_array($parts) || count($parts) < 7) {
// malformed line; ignore
var_dump([
"malformed_cookie_line" => $line,
"parts" => $parts,
]);
continue;
}
[$domain, $includeSubdomains, $path, $secureFlag, $expiresRaw, $name, $value] = array_slice($parts, 0, 7);
// Normalize booleans and expires
$secure = strtoupper($secureFlag) === 'TRUE';
$expires = is_numeric($expiresRaw) ? (int) $expiresRaw : 0;
// Some exports prefix domain with '#HttpOnly_' inside the field as well
if (str_starts_with($domain, '#HttpOnly_')) {
$httpOnly = true;
$domain = substr($domain, 10);
}
$params = [
'domain' => $domain,
'path' => $path !== '' ? $path : '/',
'secure' => $secure,
];
if ($httpOnly) {
$params['httpOnly'] = true;
}
// Only set expires when > 0; for session cookies (0) omit it
if ($expires > 0) {
$params['expires'] = $expires;
}
$cookies[] = \HeadlessChromium\Cookies\Cookie::create($name, $value, $params);
}
if ($cookies) {
$page->setCookies($cookies)->await();
}
}Metadata
Metadata
Assignees
Labels
No labels