<?php
function detectSSL(): ?bool {
// check HTTPS protocol
if( isset($_SERVER['HTTPS']) ) {
if( 'off' !== strtolower($_SERVER['HTTPS']) ) {
return true;
}
if( 1 === (int)$_SERVER['HTTPS'] ) {
return true;
}
}
if( isset($_SERVER['HTTP_X_FORWARDED_SSL']) ) {
if( 'on' === $_SERVER['HTTP_X_FORWARDED_SSL'] ) {
return true;
}
}
if( isset($_SERVER['HTTP_X_FORWARDED_PORT']) ) {
if( 443 === (int)$_SERVER['HTTP_X_FORWARDED_PORT'] ) {
return true;
}
}
if( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) ) {
if( strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https' ) {
return true;
}
}
if( isset($_SERVER['REQUEST_SCHEME']) ) {
if( strtolower($_SERVER['REQUEST_SCHEME'] === 'https') ) {
return true;
}
}
// check server port
if( isset($_SERVER['SERVER_PORT']) ) {
if( 443 === (int)$_SERVER['SERVER_PORT'] ) {
return true;
}
}
// non-SSL
return null;
}
final class Cookie {
public static $ssl;
function __construct( ?bool $ssl ) {
self::$ssl = $ssl;
}
private static function constructCookie( iterable $c ): string {
$s = 'Set-Cookie: __Test_'. $c[ 0 ] .'='. rawurlencode( $c[ 1 ] ) .'; Expires='. date('D, d M Y H:i:s', $c[ 2 ]) . 'GMT' .'; Path='. $c[ 3 ] .'; Domain='. $_SERVER['HTTP_HOST'] .';';
if( self::$ssl ) {
$s .= ' SameSite=Strict; Secure; httpOnly;';
}
return $s;
}
public static function setCookie( iterable $d ): void {
if( isset($d[ 0 ]) ) {
foreach( $d as $dc ) {
if( is_array($dc) ) {
header(
self::constructCookie($dc), false
);
}
}
}
}
}
$cookie = new Cookie( detectSSL() );
// Example
$cookie::setCookie([
[ 'test', base64_encode('test=привет_как_бы_так'), time() + 86400, '/' ],
[ 'test1', base64_encode('test1=хрювед_как_бы_так'), time() + 86400, '/' ],
[ 'test2', base64_encode('test2=зидарасьён_как_бы_так'), time() + 86400, '/' ]
...
]);