Link to home
Start Free TrialLog in
Avatar of Branislav Borojevic
Branislav BorojevicFlag for Canada

asked on

PHP setcookie() issues saving on HTTPS

I have set 2 custom cookies to be saved when user clicks a button that runs the script to save the cookies.

The issue is that I need these to be saved through HTTPS because I am using them on a store locator page, and need a secured connection to allow for location detection to happen properly.

When I do not add TRUE for secure connection and leave code as shown below, the cookies save just fine when running through HTTP.

setcookie('lat', $_POST['lat'], time()+62208000, '/', $_SERVER['HTTP_HOST']);
setcookie('lng', $_POST['lng'], time()+62208000, '/', $_SERVER['HTTP_HOST']);

Open in new window

However, when I try to add TRUE for secure connection as shown below, it does not work properly with HTTPS running:

setcookie('lat', $_POST['lat'], time()+62208000, '/', $_SERVER['HTTP_HOST'], TRUE);
setcookie('lng', $_POST['lng'], time()+62208000, '/', $_SERVER['HTTP_HOST'], TRUE);

Open in new window


I have tried including httponly as either TRUE or FALSE as well, but nothing seems to have worked.

If anyone could give any tip about getting this resolved, I would appreciate it!

Thank you!
Avatar of lenamtl
lenamtl
Flag of Canada image

Have you tried with
$_SERVER['HTTPS']

Open in new window


HTTPS: Cookie with "Secure" will be returned only on HTTPS connections

https://www.owasp.org/index.php/Testing_for_cookies_attributes_(OTG-SESS-002)
Avatar of Branislav Borojevic

ASKER

I have tried different variations, and even tried $_SERVER['HTTPS'] but did not seem to have helped to make cookies save properly with HTTPS connection running.
First make sure the cookies work ok in regular HTTP, if not the problem may come from there.

Then set the cookies with
Secure

Open in new window

flag.

Did you set a redirection on non https using Htaccess
Post a clickable URL to one of your pages implementing this code, so people can test page + see if any solution suggests itself.
Avatar of noci
noci

Be sure to set any cookies BEFORE writig any regular output.
Cookies are i the header fields. When the normal output start the header cannot be reached again.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.