Skip to content

Instantly share code, notes, and snippets.

@bohwaz
Last active September 4, 2018 13:56
Show Gist options
  • Save bohwaz/f7c7cc08fa11399f485be3e65f19a4f4 to your computer and use it in GitHub Desktop.
Save bohwaz/f7c7cc08fa11399f485be3e65f19a4f4 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)
{
$params = array(
rawurlencode($name) . '=' . rawurlencode($value),
);
if ($expire)
{
$params[] = sprintf('expires=%d', $expire);
}
if (!is_null($path))
{
$params[] = sprintf('path=%s', rawurlencode($path));
}
if (!$is_null($domain))
{
$params[] = sprintf('domain=%s', rawurlencode($domain));
}
if ($secure)
{
$params[] = 'secure';
}
if ($httponly)
{
$params[] = 'httponly';
}
if ($samesite)
{
$params[] = sprintf('samesite=%s', rawurlencode($samesite));
}
$header = sprintf('Set-Cookie: %s', implode('; ', $params));
return header($header, false);
}
@schuhwerk
Copy link

Hi! Thanks for your code!
Used it beacause the setcookie-hack via. $path stops working in php 7.3

I had 2 problems:

  • Removed the $ before is_null in line 23.
  • couldn't specify path because rawurlencode replaces / with %2F

https://gist.github.com/tivus/1347934f782bd2b1e261493615b5444f

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment