SPL_Splinter
SPL_Splinter

Reputation: 503

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

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.

Upvotes: 5

Views: 22267

Answers (2)

Khez
Khez

Reputation: 10350

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.

Upvotes: 17

stealthyninja
stealthyninja

Reputation: 10371

@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.

Upvotes: 3

Related Questions