Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save schuhwerk/1347934f782bd2b1e261493615b5444f to your computer and use it in GitHub Desktop.
Save schuhwerk/1347934f782bd2b1e261493615b5444f to your computer and use it in GitHub Desktop.
PHP setcookie function polyfill with support for SameSite attribute (compatible with PHP 5.0+)
<?php
/**
* Setcookie function with support for SameSite
* @param string|null $samesite 'Lax' or 'Strict'
*/
function setcookie_samesite( $name, $value = '', $expire = 0, $path = null, $domain = null, $secure = false, $httponly = false, $samesite = null)
{
$header = 'Set-Cookie: '.rawurlencode($name) . '=' . rawurlencode($value).';';
$header .= $expire ? sprintf('expires=%s', gmdate('D, d M Y H:i:s \G\M\T', $expire)).'; ' : '';
$header .= $path ? sprintf('path=%s', join('/', array_map('rawurlencode', explode('/', $path)))).'; ' : '';
$header .= $domain ? sprintf('domain=%s', rawurlencode($domain)).'; ' : '';
$header .= $secure ? 'secure; ' : '';
$header .= $httponly ? 'httponly; ' : '';
$header .= $samesite ? sprintf('samesite=%s', rawurlencode($samesite)).'; ' : '';
return header($header, false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment