Smokey
Smokey

Reputation: 1897

error while setting cookies in php

This is my directory structure

main folder (public_html)
index.php

sub-folder1
   subindex1.php
   subfirst1.php

sub-folder2
   subindex2.php
   subfirst2.php

This is my directory structure. Main folder is public_html. I have two sub-folders- sub folder 1 and sub folder 2.

I am running a script in subfolder1's subindex1.php to set a cookie in subfolder2 so that it can be accessed by subindex2.php

This is what I am doing now.

After doing some backend calculations, I'm setting cookies like this from subindex1.php and then does a redirect to subindex2.php

setcookie('id', "", time() + 60 * 60 * 24 * 30, '/../sub-folder2/');
setcookie('token', "", time() + 60 * 60 * 24 * 30, '/../sub-folder2/');             
header("Location: ../sub-folder2/subindex2.php"); 

Page redirects but cookies are not being set.

Is this the way to define the cookie path?

Upvotes: 0

Views: 36

Answers (2)

user1937699
user1937699

Reputation:

from php manual

The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain . If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain . The default value is the current directory that the cookie is being set in.

setcookie('id', "", time() + 60 * 60 * 24 * 30, '/../sub-folder2/');
setcookie('token', "", time() + 60 * 60 * 24 * 30, '/../sub-folder2/'); 

change to

setcookie('id', "", time() + 60 * 60 * 24 * 30, '/');
setcookie('token', "", time() + 60 * 60 * 24 * 30, '/'); 

or you want to this only to work for sub-folder2 only then :

setcookie('id', "", time() + 60 * 60 * 24 * 30, '../sub-folder2/');
setcookie('token', "", time() + 60 * 60 * 24 * 30, '../sub-folder2/'); 

Upvotes: 1

Sujeet Sinha
Sujeet Sinha

Reputation: 2433

Your path is incorrect. By starting with /, you are starting from your root directory. Use the following:

setcookie('id', "", time() + 60 * 60 * 24 * 30, '/sub-folder2/'); // ../sub-folder2/
setcookie('token', "", time() + 60 * 60 * 24 * 30, '/sub-folder2/');  // ../sub-folder2/           
header("Location: ../sub-folder2/subindex2.php"); 

Check the manual here for any doubts.

Upvotes: 1

Related Questions