PHP setcookie fails - php

I narrowed the problem down to this statement.
if (!setcookie("cookielogin",$usernametocheck, time()+3600)) echo "cookie setup failed<br/>";
Every time I run the code it shows "cookie setup failed" on browser.
I checked the browser for cookies stored by the site and I don't see my cookie.
Can anybody help ?

add ob_start(); at the top of your page and ob_clean() after setting cookie .
<?php
ob_start();
#Code..........
#Code...........
#Code............
if (!setcookie("cookielogin",$usernametocheck, time()+3600)) echo "cookie setup failed<br/>";
ob_clean();
#code......
?>

Related

PHP Session Suddenly Stopped Working For Some Pages

I've bumped into a strange glitch. I had no problems before but now suddenly the PHP session will only work for some pages but not others.
Here is how I use the session:
ini_set('session.save_path', realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
if(!isset($_SESSION["account"])) {
// session does not exist
echo "<h1>session does not exist</h1>";
} else {
echo "<h1>session exists</h1>";
}
The same code does not longer work for some pages. For example I'm able to login just fine and use most of the tools for login. But when I created a new file testSession.php with the same content as shown above. It has lost the session for some reason.
I specifically used ini_set('session.save_path', realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session')); to solve a simmilar problem but now the problem is back... why?
The strange thing about all of this is that the one php script I wanted to trigger has worked before without a problem. What could be the issue here? Why does it suddnely not work for some pages/script, as far as I can tell I've never touched that part of the code, so I didn't even change anything.
I suggest to make a session.php file that you call in every page you need to access to sessions like:
session.php
ini_set('session.use_only_cookies', 1); // secure cookie
session_set_cookie_params(0,'/','localhost',true,true); // duration, path, domain, secure connection, httponly (secure js access)
session_start(); // start session
session_regenerate_id(); // regenerating for security issues
and then include this to your pages:
include 'session.php';
if(!isset($_SESSION["account"])) {
echo "<h1>session does not exist</h1>";
} else {
echo "<h1>session exists</h1>";
}
Make sure that u start session on every page. If you have it dynamicly, make sure that your require 'xxx'; is right. Then try deleting you phpsessionid in webdevelopment tools in chrome. At last, restart your local server - wamp, xampp etc.

PHP session variable set on page (verified) does not exist after redirect or page change

PHP 7.1.7 on Windows Server 2008 Enterprise
... I noticed there were 5 other questions here just like this with no answer. I'm getting frustrated trying to do something that's always been so easy to accomplish in other languages for me. I just want to set a session variable and then read it on another page after a redirect. That should be simple basic functionality and I do not get why I've been sitting here for 2 hours trying everything I can think of and I still can't figure it out.
Each page of my application starts with: session_start();
I have a form edit processing page I'm starting with, where on a successful edit, the user is redirected back to the index page. Before the redirect, I'm setting a session variable ('success'). At this point, the session variable is set. If I comment out the header and exit() lines and echo the session["success"] variable.
$_SESSION["success"] = "The record was inserted successfully.";
header( 'Location: index.php');
exit();
}
Register Globals does not exist in my PHP.ini file (register_globals). I tried adding "register_globals=0;" to the PHP.ini file and restarting the server but I still doid not see a "register_globals" listing on the PHP info page.
No matter what I have tried, after the redirect to the index.php page, that session variable does not exist after the redirect ($_SESSION["success"]). I'm staying inside the same domain (same folder on the server really)
After setting the session variable ('success') and proving that it is set by echoing it on the edit proccessing page followed by an exit, I can not figure out how to get the session variable to persist after a redirect or page change:
If I try and echo that 'success' session variable after a redirect, I get this:
Notice: Undefined index: success
I'm not understanding why this is so difficult? What else could I try?
Thanks for any help.
Test whether the session cookie is set properly.
$_SESSION["success"] = "The record was inserted successfully.";
// header( 'Location: index.php');
echo session_name() .': '.session_id(); // print session cookie name & value
echo '<pre>' . print_r(session_get_cookie_params() ) . '</pre>';
exit();
What do you see? Open your browser's dev tools and look at cookies set when the server echoes the info above. If there is no cookie with the name (typically PHPSESSID) and session ID value above, then either your browser is not accepting cookies or the server isn't setting them. Either one will break cookie-based sessions.
If these seem to work ok, then re-establish your redirect. On the next page (index.php in your example), take a look at which cookies are received:
// Notice: this won't work on the page setting the cookie.
// Cookie should show up on the next page
echo '<pre>' . print_r($_COOKIE) . '</pre>';
Does the session id cookie exist?
If all this works, I would then look at whether PHP is actually storing session files properly. Session data is serialized and saved to files in a folder on the server's hard drive. Take a look at your php.ini, where you should see something like:
session.save_handler = files
session.use_cookies = 1
; where on server the files should be stored. the folder should be
; readable/writeable to the PHP process. Maybe '/tmp'?
session.save_path =
If you edit your php.ini, remember to restart the server.
Update
From your comments, everything seems to be setup correctly. Remove all other code. and just have this:
page1.php
<?php
session_start();
$_SESSION = []; //start with an empty array
$_SESSION['success']= 'record saved';
$_SESSION['id'] = session_id();
header('Location: index.php');
exit;
index.php
<?php
session_start();
var_dump($_SESSION);
if(isset($_SESSION, $_SESSION['id'])):
echo 'Session ids ' . ($_SESSION['id']===session_id()? 'match' : 'do not match');
endif;
What gets var-dumped in index.php after you get redirected from page1.php?

setcookie not working 3

I am trying to set a cookie based on the returned value from an insert into mySQL. I know the insert has worked as I have a value for mysqli_insert_id($link). However, he cookie is the same before and after I attempt to run setcookie. Can anyone help? The code I am using is
echo mysqli_insert_id($link)."<br>";
print_r($_COOKIE);
echo "<br>";
setcookie("id", mysqli_insert_id($link), time() + 60*60*24);
print_r($_COOKIE);
echo "<br>";
setcookie() needs to be sent before anything is echoed out to the body of the page. For example:
echo 'test'; //At this point, headers are done, and the body has started
setcookie(...); //Fails
An alternative solution would be to use ob_start() to buffer the output into memory before outputting to the browser. You can do something like this:
ob_start();
echo 'test'; //Output is captured, and stored in memory
setcookie(...); //Nothing has been output yet, so header is set properly
ob_end_flush(); //We're done storing stuff in the buffer, output it to the browser.

PHP logout system not working. (session_destroy on MAMP)

I recently transferred my website from XAMPP to MAMP. The problem is that my logout system is no longer working. The logout widget:
Log Out
My logout page itself:
<?php
session_start()
session_destroy()
header('Location:login.php');
?>
The weird thing is that when I change something to logout.php, such as making it a simple echo statement:
<?php
echo 'test';
//session_start()
//session_destroy()
//header('Location:login.php');
?>
I still do not see 'test' in my browser; I just stay at index.php even though I have commented out the header in the page. I am 100% the link path is fine.
Wether or not I alter the logout.php file or not, I can see that the server has NOT deleted the session file in tmp/php. This is weird because I have allowed in MAC OS X everyone acces to read and write to this tmp/php folder.
OS: MAC OS X
SERVER: Apache within MAMP
PHP:5.4.4
BROWSERS: Problem occurs in both Google Chrome & Safari
(This is my maiden voyage with posting a question on stackoverflow, if you tips to improve my questioning, please let me know)
Try using this instead:
<?
session_start();
$_SESSION = array();
header("Location: index.php");
?>
I just clear $_SESSION, and it always works for me
If calling logout.php when it containts the code below does not print test then there is something else wrong and it has nothing to do with the sessions.
<?php
echo 'test';
//session_start()
//session_destroy()
//header('Location:login.php');
?>
You mention that it still shows the index.php, which makes me thing you have a rewrite rule in your .htaccess file which redirects the call from logout.php to the index. Check your htaccess file for any rules.
You can find information about htaccess on MAMP here
These are the essential parts of a logout, assuming that your scripts are using PHP sessions. Note that your logout script causes a parse error because it is missing semicolons at the end of statements. Maybe just a typo.
<?php // RAY_EE_logout.php
session_start();
// CLEAR THE INFORMATION FROM THE $_SESSION ARRAY
$_SESSION = array();
// IF THE SESSION IS KEPT IN COOKIE, FORCE SESSION COOKIE TO EXPIRE
if (isset($_COOKIE[session_name()]))
{
$cookie_expires = time() - date('Z') - 3600;
setcookie(session_name(), '', $cookie_expires, '/');
}
// TELL PHP TO ELIMINATE THE SESSION
session_destroy();
// REDIRECT TO THE HOME PAGE
header("Location: /");
exit;
HTH, ~Ray
Try using output buffer.
<?php
ob_start();
session_start();
session_destroy();
header('Location:login.php');
?>
In my case it had to do with the php code block not being defined correctly. I had <? ?> instead of <?php ?>
Hope this helps someone.
#tom.e.degroot: Last time I checked, "it didnt work" was not an error message. You'll need to describe the symptoms a little more. Please follow the guidance here: http://SSCCE.org and give us something we can install and test on our own servers. Thanks, ~Ray

php script don't refreshes in browser

I have the following php code:
<?php session_start();
....
$result=$db->query($query);
$row=$result->fetch_assoc();
$_SESSION['id']=$row['id'];
header('Location: http://www.blabla.com/successLoginPage.php');
php code on: successLoginPage.php
<?php session_start();
echo $_SESSION['id'];
Here is problem. When i do all things, i see nothing in successLoginPage.php, after approximately 10 minutes i refresh the page and see correct variable. I tried to clear the cache, ctrl+f5, shutdown the browser and computer, but nothing changes - still need to wait 10 minutes. This problem is exists in chrome and ie8.
How can i solve this problem?
Thanks in advance.
*Edit 1:
I add logout.php page with the following code: session_start();session_destroy();unset($_SESSION); When i log in successfully and receive the proper echo, i push logout link and then log in using another account - all great.
1st question - can i log in via 1st account for the 1st time and via 2nd account for the 2nd time? Is this ok?
2nd question - when i failed to log in, there again i see freeze. If i try to log in with proper account after this, i will see old information about fail login. What i need to do?
It may be somewhat obvious but... is $row['id'] actually a number/string, not NULL? :p You could try
var_dump($_SESSION['id']);
instead of
echo $_SESSION['id'];
Have you tried
session_write_close();
after setting your session variable?
First of all, you are not showing the entire code and in this case it is very important.
<?php session_start();
....
$result=$db->query($query);
$row=$result->fetch_assoc();
$_SESSION['id']=$row['id'];
header('Location: http://www.blabla.com/successLoginPage.php');
// Mystery ???
When you are calling header('Location: xxx'), it doesn't stop the script, so everything after your header is executed.
You could add the function die to prevent any other code to execute after the redirection.
<?php session_start();
....
$result=$db->query($query);
$row=$result->fetch_assoc();
$_SESSION['id']=$row['id'];
header('Location: http://www.blabla.com/successLoginPage.php');
die(); // No more code executed after this //
Solved the problem.
I deleted all login files and rewrite it from scratch and all seems to work now. Don't know where bug was.

Categories