Backend Development 4 min read

Encapsulating Cookie and Session Operations in PHP

This tutorial shows how to create reusable PHP functions for reading, writing, and managing cookies and session data, including helper utilities to streamline backend web development by abstracting common operations and handling expiration, paths, and nested session keys.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Encapsulating Cookie and Session Operations in PHP

The article demonstrates how to encapsulate common cookie and session handling logic in PHP, providing reusable functions that simplify reading, writing, and managing these data structures in backend applications.

Cookie encapsulation

The cookie function accepts parameters for the cookie name, value, expiration time, path, domain, security flags, and HTTP‑only flag. It sets the cookie immediately, supports optional expiration, and returns the stored value or null if the cookie does not exist.

/**
 * 读取或写入Cookie信息
 * @param string $name  名称
 * @param string $value 值
 * @param int $expire  秒数
 * @param string $path  路径,默认站点目录
 */
function cookie($name, $value = null, $expire = null, $path = null, $domain = null, $secure = null, $httponly = false) {
    if (! is_null($value)) {
        $path = SITE_DIR . '/';
        if (is_string($value))
            $value = trim($value);
        $_COOKIE[$name] = $value; // 让cookie立即生效
        if (! is_null($expire)) {
            return setcookie($name, $value, time() + $expire, $path, $domain, $secure, $httponly);
        } else {
            return setcookie($name, $value, 0, $path, $domain, $secure, $httponly);
        }
    } else {
        if (isset($_COOKIE[$name])) {
            return escape_string($_COOKIE[$name]);
        } else {
            return null;
        }
    }
}

Session encapsulation

The session function can both set and retrieve session values. It supports dot‑notation for nested array or object access, automatically starts the session if needed, and returns null when a key is missing.

/**
 * 读取或写入session信息
 * @param string $name 支持点分多级获取
 * @param mixed $value 设置值
 * @return string|NULL|unknown
 */
function session($name, $value = null) {
    if (! isset($_SESSION)) {
        session_start(); // 自动启动会话
    }
    if (! is_null($value)) {
        if (isset($_SESSION[$name])) {
            if ($_SESSION[$name] != $value) {
                $_SESSION[$name] = $value;
            }
        } else {
            $_SESSION[$name] = $value;
        }
        return $value;
    } else {
        if (strpos($name, '.')) {
            if (isset($_SESSION[$name])) {
                return $_SESSION[$name];
            }
            $names = explode('.', $name);
            if (! isset($_SESSION[$names[0]])) {
                return null;
            }
            $var = $_SESSION[$names[0]];
            $len = count($names);
            for ($i = 1; $i < $len; $i ++) {
                if (is_array($var)) {
                    if (isset($var[$names[$i]])) {
                        $var = $var[$names[$i]];
                    } else {
                        return null;
                    }
                } elseif (is_object($var)) {
                    if (isset($var->{$names[$i]})) {
                        $var = $var->{$names[$i]};
                    } else {
                        return null;
                    }
                } else {
                    break;
                }
            }
            return $var;
        } else {
            if (isset($_SESSION[$name])) {
                return $_SESSION[$name];
            } else {
                return null;
            }
        }
    }
}

Session existence check

The helper issetSession ensures the session is started and returns a boolean indicating whether a given session key exists.

// 检查会话参数是否存在
function issetSession($name) {
    if (! isset($_SESSION)) {
        session_start(); // 自动启动会话
    }
    return isset($_SESSION[$name]);
}

The article concludes with a brief call for readers to like and share the content.

backendWeb DevelopmentPHPcookiesession
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.