Skip to content
← Back to Snippets
Code

Set a Cookie

Sets a cookie with explicit expiry, path, secure, HttpOnly, and SameSite options when headers are still open.

Purpose

Sets a cookie with explicit expiry, path, secure, HttpOnly, and SameSite options when headers are still open.

Snippet details

ContextCookieLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Security

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Set a Cookie.
 *
 * Purpose:
 * Sets a cookie with explicit safety options.
 *
 * @param string $name Cookie name.
 * @param string $value Cookie value.
 * @param int $seconds_to_live Cookie lifetime in seconds.
 * @return array Cookie set result.
 */
function ogSnippetSetACookie(string $name, string $value, int $seconds_to_live): array {
	$result = array(
		'ok' => false,
		'message' => 'Cookie was not set.'
	);

	$name = trim($name);

	if ($name === '' || headers_sent() === true) {
		return $result;
	}

	if ($seconds_to_live < 1) {
		$seconds_to_live = 3600;
	}

	$options = array(
		'expires' => time() + $seconds_to_live,
		'path' => '/',
		'secure' => true,
		'httponly' => true,
		'samesite' => 'Lax'
	);

	if (setcookie($name, $value, $options) === true) {
		$result['ok'] = true;
		$result['message'] = 'Cookie header was queued.';
	}

	return $result;
}

$cookie_result = ogSnippetSetACookie('og_stargate_visit', 'alpha-site', 3600);

echo 'Set cookie result: '.$cookie_result['message'];