5

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.

SPL_Splinter
  • 483
  • 1
  • 5
  • 16

2 Answers2

16

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.

Eliasz Kubala
  • 3,836
  • 1
  • 23
  • 28
Khez
  • 10,172
  • 2
  • 31
  • 51
  • Thanks for your help. It really worked. Sorry for taking so much time to accept it, though. You've answered like 4 days ago. โ€“ SPL_Splinter Apr 11 '11 at 11:57
3

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

stealthyninja
  • 10,343
  • 11
  • 51
  • 59