You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Utils/Cookie.php

107 lines
3.0 KiB
PHP

<?php
namespace App\Utils;
use App\Services\Config;
class Cookie
{
private static function isSecureRequest()
{
$mode = strtolower(trim((string) Config::get('cookie_secure', 'auto')));
if (in_array($mode, ['1', 'true', 'yes', 'on'], true)) {
return true;
}
if (in_array($mode, ['0', 'false', 'no', 'off'], true)) {
return false;
}
if (!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off') {
return true;
}
if (isset($_SERVER['SERVER_PORT']) && (int) $_SERVER['SERVER_PORT'] === 443) {
return true;
}
if (isset($_SERVER['REQUEST_SCHEME']) && strtolower((string) $_SERVER['REQUEST_SCHEME']) === 'https') {
return true;
}
if (Config::get('cookie_trust_forwarded_proto', 'false') === 'true') {
$forwardedProto = isset($_SERVER['HTTP_X_FORWARDED_PROTO'])
? strtolower(trim(explode(',', (string) $_SERVER['HTTP_X_FORWARDED_PROTO'])[0]))
: '';
return $forwardedProto === 'https';
}
return false;
}
private static function sameSite($secure)
{
$sameSite = ucfirst(strtolower(trim((string) Config::get('cookie_samesite', 'Lax'))));
if (!in_array($sameSite, ['Lax', 'Strict', 'None'], true)) {
$sameSite = 'Lax';
}
// Browsers reject SameSite=None cookies unless Secure is also enabled.
return $sameSite === 'None' && !$secure ? 'Lax' : $sameSite;
}
private static function options($time, $domain = '')
{
$secure = self::isSecureRequest();
$options = [
'expires' => (int) $time,
'path' => '/',
'secure' => $secure,
'httponly' => true,
'samesite' => self::sameSite($secure),
];
if (trim((string) $domain) !== '') {
$options['domain'] = trim((string) $domain);
}
return $options;
}
public static function set($arg, $time)
{
foreach ($arg as $key => $value) {
setcookie($key, $value === null ? '' : (string) $value, self::options($time));
}
}
public static function setwithdomain($arg, $time, $domain)
{
foreach ($arg as $key => $value) {
setcookie($key, $value === null ? '' : (string) $value, self::options($time, $domain));
}
}
public static function startSession()
{
if (session_status() !== PHP_SESSION_NONE) {
return;
}
$secure = self::isSecureRequest();
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'secure' => $secure,
'httponly' => true,
'samesite' => self::sameSite($secure),
]);
session_start();
}
public static function get($key)
{
if (isset($_COOKIE[$key])) {
return $_COOKIE[$key];
}
return "";
}
}