Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
}
@tivus

This comment has been minimized.

tivus commented Sep 4, 2018

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