Set cookie in different folders - php

I'm trying to create cookie from one folder that will also work in another.
Simply doing:
setcookie('favorite['.$id.']',1,time()+60*24*60*60,'/');
But it doesn't work. Cookies are visible in the created folder but empty in other.
Also I've tried:
setcookie('favorite['.$id.']',1,time()+60*24*60*60,ROOT);
setcookie('favorite['.$id.']',1,time()+60*24*60*60,HTTP_ADR);
Where ROOT = dirname(__FILE__) and HTTP_ADR is address of my site in http://example.com/site
Could it be due to problem of this array favorite['.$id.'] ?
UPDATE: using in this way echo count($_COOKIE['favorite'])

In case its not working you can store that cookie in the session and can use that cookie
<?php
session_start();
if(isset($_COOKIE['cookiename']))
{
$_SESSION['cookie_name']= $_COOKIE['cookiename'];
}
echo $_SESSION['cookie_name'];
?>

Strange.
This script which in /cookie/ foolder
<?
setcookie('foo[lol]', 1, time()+60*24*60*60, "/");
sets cookie which works even in root folder.
So make shure nothing deletes your cookies in another folder.
EDIT: php can't read cookies which contain brackets. But browsers can.
EDIT2: no, it can, but it thinks that it is array. So to read your cookie use this code:
var_dump($_COOKIE['favorite'][$id]);

Related

PHP How can I set a default path to cookies

I'd like to know if there's anyway I can set default path to cookies, so I doesn't need to specify it on setcookie function call, I tried on php.ini file, but it's not working as I supposed.
When I check out my cookies on firebug, I get that: FireBug PrintScreen
I need both to be the same value, so if I put the code bellow on any file at "/loja", it works.
setcookie("PHPSESSID", $_COOKIE['PHPSESSID'], 0, "/");
But the problem is, I have the same code working on different areas, so I'm pretty sure it's something wrong on server side config.
I hope made myself clear, any insight about it would be great.
You're making a mistake by manipulating phpsessid directly.
Use session_name instead:
session_name("sessionExampleName"); //Use diferent names for each application
session_start();
To get or set a session id:
//Set:
session_id('newid');
session_start();
//Get
session_start();
$id = session_id();

setcookie not setting for the following code

set cookie is not setting the value for the following code.
<?php
session_start();
ob_start();
unset($_SESSION['adminname']);
session_destroy();
if(isset($_COOKIE['adminremember_me'])) {
$past = time() - 100;
setcookie('adminremember_me', gone, $past);
}
header("Location: login.php");
exit();
?>
Cookie is not deleting as setcookie donot works though an error message is not displayed.
Interesting part is that i have another file with same code structure but with different cookie name for normal user logout and that one works.
I moved the admin logout file which was in (htdocs/site/admin/)to (htdocs/site) and now logout works!!! seriously what change didit make?
You can have multiple cookies with the same name but different paths. So if you script is in /folder1/folder2/mypage.php, you can have 1 cookie with the path /folder1 and another with the path /folder1/folder2, and both cookies could have the same name.
My guess is the cookie you are trying to delete belongs to a different path (by default, if you don't specify a path, then it assumes the folder that the script is in). To delete it, you will have to manually set the path parameter to match that of the cookie. For example:
setcookie('adminremember_me', gone, $past, "/");
or
setcookie('adminremember_me', gone, $past, "/folder1/");
To see what the path is on the existing cookie, you need to use your browser's cookie viewer to see what path is set on it.
Edit: to answer the question in your edit, when you moved the location of your logout file, you moved it to be in the same folder as the path that was set on the cookie (so the default value was now the same). If you want to move the script back to the old location, just explicity set the path to whatever the folder was where it worked

session not working when communicating with localhost

If I navigate to 'sub.domain.com/session_test.php' in browser, the session are saved and work fine. I can see all the sessions on page refresh.
However, if I make an http post request from javascript in localhost to the same URL, the sessions are not being saved because I dont get any data(data in the "if" statement) back.
Any ideas why this is happening?
session_start();
if(isset($_SESSION['u'])){
var_dump(ini_get('session.save_path'));
var_dump(ini_get('session.gc_maxlifetime'));
var_dump(ini_get('session.cookie_lifetime'));
echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>';
die();
}
$_SESSION['u'] = "34343gf";
die('end');
The PHP Session variable is server side. Cookies only store the session id in order to retrieve the correct session information.
Anyway, assuming:
sub.domain.com/session_test.php is an alias to localhost/session_test.php (they point to the same file)?
You can't read cookies from one domain in another domain, even if they resolve to the same server. However, there are ways to corcumvent this. One way is to pass the cookie session id as a GET param, although this is not very safe.
Another way is to store the session ID locally (in a text file, or the database) and retrieve it later.
I try your code with a pair of files named index.php and index2.php.
The session is working. (Windows7, Wamp2.5, Apache2.22, php5.4)
I think you have no rights into your /tmp folder where the session is.
Try to put a file inside it with php function file_put_contents( ini_get('session.save_path')."/test-file.txt", 'Test file is OK');.
Your code is OK.

Using $_SESSION between pages that are in different directories

I was wondering how I would pass something using a session between pages that are in two separate directories. For example, if I had the following code, what would I need to add to make it work?
Page 1: directory\directory1\directory2\Page1.php
session_start();
$_SESSION['example'] = '123';
Page 2: directory\dir1\dir2\Page2.php
session_start();
echo $_SESSION['example'];
Your code should work if these pages are served within the same domain.
You do not have to session_start() in each page. Just write that, in a single file and share that file between the pages you want to hold the session in.
So, if you have page1.php and page2.php and session.php You can create session either in page1.php and check it in page two like: echo var_dump($_SESSION) and vise-versa
First of all, check if session-cookies are properly set. Some problems (e.g. Headers already sent) may cause your session cookie to not be set.
If this is working properly, you may have to change the session cookie parameters via session_set_cookie_params
By setting the second parameter (path) to /, the session cookie is valid for the root of your website and all subdirectories.
Example
session_set_cookie_params(0, '/');
The same settings can also be set in your php.ini or via ini_set(). See Session configuration
Note:
I'm not sure if these settings have any effect if session.autostart is enabled, in which case the cookie-header may already be sent before the changes are made.

PHP Sessions data lost when changing directory?

I've got a simple login system using PHP sessions, but just recently it seems that if you visit pages not in a certain directory (/login/) you will always be flagged as not logged in, even when you are. It seems that my session data is being lost when I change directories (say, to /login/user/).
I don't think I've touched the code myself since the problem appeared, is there something my web host could have done to my PHP installation that would delete the session data, and is there a workaround?
EDIT:
Inside each file that needs authorization, it loads a loginfunctions.php file which calls session_start() and checks the login. Files which work in /login and i copy and paste into /login/user stop working, even though i update all the relevant paths and links.
EDIT2:
Okay, some code.
In the actual pages that are giving me the error, this is the auth. code:
require_once("../../../includes/loginFunctions.php");
$login = new login;
$login->checkLogin(0);
Inside loginFunctions.php is this:
class login{
function checkLogin($requiredAccess){
session_start();
if($_SESSION['accesslevel'] < $requiredAccess || $_SESSION['logged_in'] != TRUE){
die("You don't have access to this area. If you should have access, please log in again. <a href='/login/'>Login</a>");
}
if (isset($_SESSION['HTTP_USER_AGENT'])){
if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT'])){
session_destroy();
die("Bad session. Please log in again. <a href='/login/'>Login</a> ");
}
} else {
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
}
if (!isset($_SESSION['initiated'])){
session_regenerate_id();
$_SESSION['initiated'] = true;
}
}
}
The $requiredAccess variable is the access level that you need to access this page, so if you have an accesslevel of 3 in the database you can view level 0, 1, 2 and 3 pages. This is specified when the function is called in the main page and is compared to the access level of the current user which is defined in $_SESSIONS when they log in.
I'm getting the error 'You don't have access to this area etc." when i try to access these pages. If i try to print the $_SESSION variables, nothing shows; they appear to be empty. However, if I move the file to the /login/ folder (one level up) and update the links, they work perfectly and all the variables print out fine. This makes me think the code is not the part that's not working, but some setting in my PHP install that has been changed without my notice.
maybe you aren't calling session_start() at the begging of pages not in /login/ ..?
I had a similar problem.
Check you don't have a php.ini file. Removing this sorted the problem out. Still looking ito exactly why. The php.ini file could even be blank and it would stop session data from carrying over to more than one directory...
It's possible that they changed the php.ini setting session.cookie_path.
You should call session-set-cookie-params before you call session_start and make sure you set the cookie path yourself. Set it to the highest level directory you want the session to be valid for. EG if you set it to /login it will be valid for /login and /login/user. If you want your session to be valid for the etire site set the path to be /
i had a similar issue. you may want to use:
<?
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", ".example.com", 1); ?>
or something similar. i know cookie and session variables are a different desired solution, but this was able to clear up my issue.
See here for documentation
Make sure you have the same php.ini file in each directory that you want to access the session variables from.
This is why you shouldn't use directory to make false friendly URLs...
Don't forget to call session_start() every time you need the session.

Categories