Storage state
Save cookies and storage to a JSON file, then reuse them in a fresh browser context.
This example saves browser state to a JSON file, then opens a second context with that state loaded.
Use the same pattern after a real login flow when login itself is not the behavior under test.
Run it
php content/examples/storage-state.php
Expected output:
Saved state: .../var/playwright-artifacts/examples/state.json
Reused cookie: yes
The example uses a synthetic cookie on example.com so it can run without a test account.
What it demonstrates
addCookies()seeds state in a context.saveStorageState()writes cookies and storage to JSON.storageStateloads that JSON into a fresh context.- State files belong in artifacts or ignored
.auth/directories, not in commits.
Go next
Source
storage-state.php<?php
declare(strict_types=1);
/*
* This file is part of the community-maintained Playwright PHP project.
* It is not affiliated with or endorsed by Microsoft.
*
* (c) 2025-Present - Playwright PHP - https://github.com/playwright-php
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require_once __DIR__.'/../../vendor/autoload.php';
use Playwright\Playwright;
$artifactDir = __DIR__.'/../../var/playwright-artifacts/examples';
is_dir($artifactDir) || mkdir($artifactDir, 0777, true);
$statePath = $artifactDir.'/state.json';
$context = Playwright::chromium(['headless' => true]);
$context->addCookies([
[
'name' => 'example_session',
'value' => 'demo',
'url' => 'https://example.com',
],
]);
$context->saveStorageState($statePath);
$context->close();
$reused = Playwright::chromium([
'headless' => true,
'context' => [
'storageState' => $statePath,
],
]);
$cookies = $reused->cookies(['https://example.com']);
$hasCookie = false;
foreach ($cookies as $cookie) {
if ('example_session' === ($cookie['name'] ?? null)) {
$hasCookie = true;
break;
}
}
echo 'Saved state: '.$statePath.PHP_EOL;
echo 'Reused cookie: '.($hasCookie ? 'yes' : 'no').PHP_EOL;
$reused->close();