Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a cookie to the entire domain from a page inside a folder

Tags:

php

setcookie

I'm a begginer in cookies and stuff like that.

I need to set a cookie to the entire domain from a page inside a folder like mydomain.com/folder/page.php. I had to do this before and I got it done redirecting to another page mydomain.com/another.php which set the cookies. The thing is now I should not redirect the page because of some data coming from a form and other things, so how could I do this?

setcookie("name", $name, time()+31536000); will set the cookies only for the pages inside folder and I tried setcookie("name", $name, time()+31536000,'/','mydomain.com'); but it didn't worked.

like image 787
SPL_Splinter Avatar asked Dec 09 '22 09:12

SPL_Splinter


2 Answers

This code definitely works:

setcookie("name", $value, time()+31536000,'/');

You should take note that mydomain.com is different from www.mydomain.com or sub.mydomain.com.

Other than this, take note that the value of $value should be a string.

like image 122
Khez Avatar answered Mar 22 '23 22:03

Khez


@SPL_Splinter: Make sure you're setting the cookie prior to any output. So, for example:

<?php
$name = 'Some name';

setcookie("name", $name, time() + 31536000, '/', '.mydomain.com');
if (isset($_COOKIE['name'])) 
{
    echo $_COOKIE['name'];
}
?>

Update

From http://php.net/manual/en/function.setcookie.php

The domain that the cookie is available to. To make the cookie available on all subdomains of example.com (including example.com itself) then you'd set it to '.example.com'. Although some browsers will accept cookies without the initial ., » RFC 2109 requires it to be included. Setting the domain to 'www.example.com' or '.www.example.com' will make the cookie only available in the www subdomain.

like image 41
stealthyninja Avatar answered Mar 22 '23 23:03

stealthyninja