Skip to content
← Back to Snippets
Code

Set and Get a Session Variable

Sets one allowlisted session key, reads it back, and returns a clear status without storing credentials or raw sensitive data.

Purpose

Sets one allowlisted session key, reads it back, and returns a clear status without storing credentials or raw sensitive data.

Snippet details

ContextSessionLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Sessions and Authentication

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 and Get a Session Variable.
 *
 * Purpose:
 * Stores a single session value under a safe key and reads it back so callers
 * can confirm the value was written.
 *
 * @param string $session_key Session key using letters, numbers, and underscores.
 * @param string $session_value Value to store.
 * @return array Write status and retrieved value.
 */
function ogSnippetSetAndGetASessionVariable(string $session_key, string $session_value): array {
	$session_key = trim($session_key);

	if (preg_match('/^[A-Za-z][A-Za-z0-9_]*$/', $session_key) !== 1) {
		return array(
			'ok' => false,
			'value' => '',
			'error' => 'invalid_session_key'
		);
	}

	if (session_status() !== PHP_SESSION_ACTIVE) {
		if (headers_sent() === true) {
			return array(
				'ok' => false,
				'value' => '',
				'error' => 'session_not_started'
			);
		}

		session_start();
	}

	$_SESSION[$session_key] = $session_value;
	$retrieved_value = '';

	if (isset($_SESSION[$session_key]) === true) {
		$retrieved_value = (string) $_SESSION[$session_key];
	}

	return array(
		'ok' => true,
		'value' => $retrieved_value,
		'error' => ''
	);
}

$session_value_report = ogSnippetSetAndGetASessionVariable('last_patrol_ship', 'Battlestar Pegasus');

echo 'Stored session value: '.$session_value_report['value'];