My cookie is set but php can't read it - php

I've been trying to make a cookie autologin, but although the cookie is set, php can't read it. I know it is set because I can see it with Cookie Monster, I don't know what's wrong...
Need help! It's driving me crazy!
The code to set the cookie (I do it before any HTML tag)
setcookie("autologin", $_SESSION['user'], time()+5184000, "/");
the code to retrieve it:
if (!isset($_SESSION['user']) && isset($_COOKIE['autologin'])) {
$_SESSION['user']=$_COOKIE['autologin'];
}
UPDATE: I don't use the code above in the same script. I do login, close the browser, reopen it and try to get the cookie, cookie is in Cookie Monster but php can't see it.
FIX: My problem was I was trying to save a serialized object, $_SESSION['user'], in the cookie, it has been fixed with that:
setcookie("autologin", base64_encode($_SESSION['user']), time()+5184000, "/");
and retrieving with:
if (!isset($_SESSION['user']) && isset($_COOKIE['autologin'])) {
$_SESSION['user']=base64_decode($_COOKIE['autologin']);
}

This cookie will available on next page loading. In this page you can define it yourself.

My problem was I was trying to save a serialized object, $_SESSION['user'], in the cookie, it has been fixed with that:
setcookie("autologin", base64_encode($_SESSION['user']), time()+5184000, "/");
and retrieving with:
if (!isset($_SESSION['user']) && isset($_COOKIE['autologin'])) {
$_SESSION['user']=base64_decode($_COOKIE['autologin']);
}

Related

PHP $_COOKIE get cookie with preset variable

SOLUTION:
$_COOKIE was replacing periods with underscores.
str_replace('.','-',$cookie_name);
PROBLEM
I am setting a cookie like this.
$cookie_name = '_visited-'.$user_ip.'-'.$visted_link;
setcookie($cookie_name,'visited',time() + (86400 * 30), "/");
header('Location: '.$_SERVER['REQUEST_URI']);
exit;
then trying to see if cookie is set and unlink it from links array like this.
foreach($links['unique'] as $link){
$cookie_name = '_visited-'.$user_ip.'-'.$link;
if(isset($_COOKIE[$cookie_name])){
if(($key = array_search($l, $links['unique'])) !== false) {
unset($links['unique'][$key]);
}
}
}
odd thing is that even though the cookie is clearly set in the foreach using isset I am unable to detect that the cookie exist so I am unable to remove the visited link.
You can not access the cookie on the same page it is set.
As you can see in the manual it clearly states it:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array.
How do you transfer $links from one page to the other? Each call of the PHP is independent. That is why I save my cookies to a session table in the database. First step in each page is to load the sessions from the database.
I think your cookie is never found since $links is initiated at each execution. Add print_r($links) at the top of the page to see, and edit your question.
ok so found the issue. I was putting user IP in as part of the cookie name.
The . was being replaced by _ so just went ahead and replaced all . with - when setting the cookie. Works perfectly as I had intended now.

Why can't I set a cookie in PHP which can be used in an If statement on the next page?

I'm trying to create a cookie within PHP.
By using the following code :
<?php
//Writing Cookie Data
setcookie("Enabled", "True", time()+3600);
setcookie("Username", $username);
//Test if cookie is set. / Just for test purposes.
echo $_COOKIE["Username"];
?>
After the cookie is set I've used a code to let users go to the next page by pressing an image (link).
This one :
<img src="image.png"></img>
And I've used a code on the next page which will check if the cookie exists.
This one :
<!-- Security Start -->
<?php
If (isset($_COOKIE["Enabled"])) {
}
else
{
header("Location: ../");
}
?>
<!-- Security Stop -->
And when the user goes to the next page he'll just be redirected to the folder specified if the security cookie doesn't exist.
I've probably setup everything correctly, and I've already checked many things, but I can't come up with a solution to this problem. The cookie should exist, and exsists.
Because the echo code works on the same page.
But after going to the next page; the cookie is suddenly gone, it doesn't exist.
Echo and using it in an If statement on the next page are both not possible.
Any ideas what might cause this?
Cookies
Some things I would do to debug this if you want cookies:
I would check the path as stated by Patrick
I would look at the return value of setcookie and see if it tells you it failed.
In your browser you should be able to see a list of all cookies, and you can check and see if the cookie was actually set. Again, look at the path here.
Using a session instead
However, I agree with the session recommendation by developerwjk, one way to do it is to make sure you call 'ob_start()' as one of the first things that happens on the page, it will then buffer the output and give you time to manipulate $_SESSION. Make sure you then call ob_flush(), to flush the buffer once you are finished with all session stuff.. I believe otherwise it will automatically flush the buffer at the end of the page but it might just discard everything..
You do not see the cookie because you have not set the PATH argument for setcookie
Using a path of "/" will enable the use of the cookie anywhere on the domain, otherwise the cookie can only be seen by scripts in the folder and sub folders of the executing script.
setcookie("Enabled", "True", time()+3600, "/");
setcookie("Username", $username,time()+3600,"/");
But as with the comments do not use cookies in place of sessions, as cookies can be easily faked.
If you already have session started you do not need to do session_start() again, if you have php 5.4 or higher you can check session status with session_status
if (session_status() !== PHP_SESSION_ACTIVE) {session_start();}
or if it is lower than 5.4
if (!isset($_SESSION)) { session_start(); }
As per the user submitted comment on the session_status page

Session variable not being saved from $_REQUEST

I think i'm missing something obvious. I have a session started at the very top of my page. Below that i have the following code. The var dump out puts "one" when it is displayed from the requested page. After refresh the var dump out puts NULL. Why is this not getting saved?
if($_REQUEST["page"] == 1) {
$_SESSION["one"] = true;
}
var_dump($_SESSION["one"]);
If you have session_start() at the top of your page, as you claim, then your code should look something like this:
session_start();
if($_REQUEST["page"] == 1) {
$_SESSION["one"] = true;
}
var_dump($_SESSION["one"]);
This should 100% work, no question. There IS something else stopping this from working in your code that you have not supplied. My first guess would be a session destroy of some kind.
First, you need to ensure you start the session before attempting to use it. Secondly, it is recommended that you specify either POST or GET instead of generally using REQUEST. If you want to support either GET or POST, you might do something like this:
// Begin Session Management
session_start();
// Check both GET and POST for the parameter
if($_GET['page'] == 1 || $_POST['page'] ) {
// Modify the session
$_SESSION["one"] = true;
}
// See what we ended up with in the session.
var_dump($_SESSION["one"]);
This works for me, but I'm using memcache as my session session handler. Verify your own session handler in php.ini, and ensure that the session handler is working properly. Also, ensure you are closing the session properly if you are redirecting, setting a new location, or exiting in unusual ways.

Telling a php session's name?

I installed a pre-built forum on my website and I want (in a diffrent page) to check if the forum's session is active.
Something like :
if (isset($_SESSION['forum'])) { echo "Session is active!"; }
Problem is - I don't know the sessions name...
Tried downloading some chrome add-ons for session managing but I can't get the name of the session.
Whats the right way of doing this?
Thanks ahead!
You can see the dump of $_SESSION variable
var_dump($_SESSION);
session_name() will give you the session name, that usually is defined in php.ini. By default it is always: PHPSESSID. This name is used as cookie name or as POST/GET variable name.
session_id() will give you the identifier for the current session. It will be the contents of the cookie or POST/GET variable.
Then you have $_SESSION that will contain all your session data. use print_r() to see what you have stored in it so far.
To know if session vars are set you can also just do if(isset($_SESSION)&&count($_SESSION))
try
print_r ($_SESSION);
taht way you'll see all sessions
<?php
session_start();
print_r($_SESSION);
?>
Use this to see which session variables are currently set.
You need to check that the session is currently active, and then that the forum key is defined
if ( ! ($sid = session_id()) {
session_start(); // open session if not yet opened
$sid = session_id(); // get sid as session ID
}
// $sid contains the session ID (in cookie)
if (isset($_SESSION['forum'])) {
// forum is defined
}
See also the answer from this page

PHP Session not Saving

I have this written at the very first line on every page of my website.
include("restd.php");
and restd.php contains the following lines :
#session_start();
if(isset($_SESSION['id']))
{
}
else
{
header("location:index.php");
}
The problem i'm facing is that when ever i click or do something on my website. it logs me out and takes me to index.php.
im sure its something to do with the session. ive tried every single thing to avoid this problem but i ahve used restd.php because i dont want anyone to copy the url of someone and paste and get into the website.
anyone who is logged in only can view other's pages. if they arent logged in then they'll be redirected to index.php
EDIT : and guys a confusing thing is that all this is working fine on my testing server which is easyPHP-5.3.8.0 but this problem is coming up when i upload all the files to my server.
Your session directory (probably /tmp/) is not writable.
Check with session_save_path() if it is writable.
if (!is_writable(session_save_path())) {
echo 'Session path "'.session_save_path().'" is not writable for PHP!';
}
Do you actually set $_SESSION['id'] on a page...
What you are trying to do here is:
Start a session and load the $_SESSION from the session handler
Check if $_SESSION contains key 'id'
Redirect to index.php if $_SESSION['id'] is not set
Do you actually do this in index.php?
session_start();
$_SESSION['id'] = something;
you need declare $_SESSION['id'] :
file1.php
session_start();
$_SESSION['id'] = '123'
file2.php
include 'file1.php'
if(isset($_SESSION['id']))
{
}
else
{
header("location:index.php");
}
In my case I forgot that I had the PHP flag session.cookie_secure set to on, while the development environment was not TLS-secured.
More information about Session/Cookie parameters.
I know this is an old thread, but the following helped me with the same problem after hours of despair. Found on: http://php.net/manual/de/function.session-save-path.php
I made a folder next to the public html folder and placed these lines at the very first point in index.php
Location of session folder:
/domains/account/session
location of index.php
/domains/account/public_html/index.php
What I placed in index.php at line 0:
<?php
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
?>
Hopefully this will save you time.
Check maybe your session path does not exist
so you can save PHP session path using:
ini_set(' session.save_path','SOME WRITABLE PATH');
Couple things:
your include file doesn't have the <?php ?> tags, so the content will not be evaluated as PHP
Session_start must be called before you start outputting anything. Is that the case?
You still don't even answer where you SET $_SESSION['id']. $pid = $_SESSION['id'] does not set the session variable. session_start() comes before ANYTHING session related, it's not shown before your include.
I had the same problem and found a work-around for it. If anybody can explain why the session is not read even when the cookie is there, please let me know.
<?php
// logged.php
// The PHP session system will figure out whether to use cookies or URLs to pass the SID
if(!isset($_COOKIE['PHPSESSID']) && !isset($_GET['PHPSESSID']) && authenticationRoutine(/* Returns true if succesfully authenticated */) ) {
session_id(uniqid("User--"));
session_start();
$_SESSION['id']=session_id();
}
?>
<?php
// Insecure restd.php (The user can forge a stolen SID cookie or URL GET request, but that is inherent with PHP sessions)
if(!isset($_COOKIE['PHPSESSID']) && !isset($_GET['PHPSESSID']) {header('Location: index.php')}
?>
.
[EDIT]
Even though the cookie was there and I prevented starting a new session, the session had not been read and started, so no session variables were available. In this case I check if the session has been started first (not using session_status() because it doesn't exist in PHP 3.5, which for some reason is the most widespread among hosts). If no session has been started within PHP, I check if it had been started before by testing the cookies and GET variables. If a session ID was found, the script resumes the session with that ID. If no ID is available, the user gets redirected to the index.
<?php
// restd.php
if(empty(session_id())) {
if(isset($_COOKIE['PHPSESSID']) && !empty($_COOKIE['PHPSESSID'])) {session_id($_COOKIE['PHPSESSID']);}
elseif(isset($_GET['PHPSESSID']) && !empty($_GET['PHPSESSID'])) {session_id($_GET['PHPSESSID']);}
else {header('Location: index.php'); exit(0);}
session_start();
}

Categories