I am setting a cookie on one page with below code
setcookie(codeDone,true);
This works but then I reset it to false on another page
setcookie(codeDone,false);
But then, when I go back to the first page, before the part that sets it to true I have
if($_COOKIE['codeDone'] == true){
$cookie = $_COOKIE['codeDone'];
$done = false;
echo"cookie set to $cookie";
}
setcookie(codeDone,true);
For some reason the ocokie is set to true because the contents of this if are always executed
Why is the cookie returning true (1) if in the previous page i set it to false?
Cookies are only string-values.
The code below is an example for your case to handle string as boolean:
ob_start();
if (isset($_COOKIE['codeDone'])) {
//this is your magic
$result = filter_var($_COOKIE['codeDone'], FILTER_VALIDATE_BOOLEAN);
if ($result === true) {
$cookie = $_COOKIE['codeDone'];
$done = false;
echo "Current Cookie Status: ".$_COOKIE['codeDone'];
}
}
setcookie('codeDone', 'true');
ob_end_flush();
BTW: You cannot modify the header (setcookie) after executed echo. this is the reason why i use the output buffer (ob_start/ob_end_flush)
Related
Hi,
I need to create a session as soon as the visitor enters my page. Then by clicking on a link that takes to an URL like this example.org/page?no_redirect=true the session must be destroyed but the session should be created again if they click on a link to this URL example.org/page?no_redirect=false.
I did it like this:
session_start();
$_SESSION['redirect'] = "false";
if($_GET['no_redirect'] == "true")
{
$_SESSION['redirect']="true";
} elseif ($_GET['no_redirect'] == "false") {
$_SESSION['redirect']="false";
}
if ($_SESSION['redirect']!=true) {
$redirect = <<<EOF
<script type='text/javascript'>DM_redirect("mobile/$page");</script>
EOF;
}
but its not working. What could it be?
Thank you.
The check if ($_SESSION['redirect'] != true) makes no sense, because you are comparing a non-empty string to a boolean. Non-empty strings always evaluate to true, so your check is really if (true != true), which means the content inside the block will never be executed.
A more sensible approach would be to unset your session once its purpose has been served instead of setting it to "true" / "false".
Code:
session_start();
# Check whether the session should be unset.
if ($_GET['no_redirect'] == "true") {
unset($_SESSION['redirect']);
}
# Check whether the session should be set.
else if ($_GET['no_redirect'] == "false") {
$_SESSION['redirect'] = "true";
}
# Check whether the session is set.
if (isset($_SESSION['redirect'])) {
$redirect = <<<EOF
<script type='text/javascript'>DM_redirect("mobile/$page");</script>
EOF;
}
I'm currenting busy coding a registration page. The page has three steps and every step has its own cookie value. What I'd like to do is checking for the cookies value and transfer the user to the correct page upon visiting the website
Example:
if the value of $_COOKIE['step'] is 'step_two' it should redirect to: www.domain.com/register.php?step=your_details. If the cookie's not set, it should not redirect and stay on the register.php page.
The redirecting is working 'fine', but it gets into an infinite loop. I really cant think clear anymore as I've been awake for almost 24h now. Therefor I would appreciate it if anyone could push me into the right directions.
Piece of code:
$cookie_value = 'step_2';
setcookie("step",$cookie_value, time()+3600*24);
$cookie_not_set = true;
$cookie_step_two = false;
if (isset($_COOKIE['step'])) {
if ($_COOKIE['step'] == 'step_2') {
$cookie_not_set = false;
$cookie_step_two = true;
header('Location: ?step=your_details');
exit();
}
} else {
$cookie_not_set = true;
}
Thank you.
Nowhere are you actually setting your cookie value, so it won't change. That's why you have an infinite loop.
$_GET and $_COOKIE have nothing to do with each other. It looks like you want:
if ($_GET['step'] === 'your_details')`
...which would be better than using a cookie anyway.
You are going to constantly enter your if condition as there is no other manipulations going on to your cookie data.
if your cookie is set to "step_2" you will enter the loop. No changes are in place, so on the refresh to the page. You will re-enter the step_2 condition and be into a redirect.
I'm also assuming that you understand that your $_GET & $_COOKIE requests are completely different. If not, see #Brads answer
A solution to stop this infinite loop would be:
if (isset($_COOKIE['step'])) {
if ($_COOKIE['step'] == 'step_2') {
$cookie_not_set = false;
$cookie_step_two = true;
$_COOKIE['step'] = 'step_3';
header('Location: ?step=your_details');
exit();
}
But also take note, your true/false validations/changes are local changes and will not be absolute on page refresh
I believe your issue is the redirect is not changing your cookie, so you need to look at the GET var you a re passing if the cookie is set to step_2 thus;
$cookie_not_set = true;
$cookie_step_two = false;
if (isset($_COOKIE['step'])) {
if ($_COOKIE['step'] == 'step_2') {
if( !empty($_GET['step']) && $_GET['step'] == 'your_details' )
{
... you have redirected and now can continue ...
}
else
{
// redirect and set the get var to signal to this script.
$cookie_not_set = false;
$cookie_step_two = true;
header('Location: ?step=your_details');
exit();
}
}
} else {
$cookie_not_set = true;
}
For months I've been using the following code without a problem to track unique sessions on my site, but it has recently just stopped working for an unknown reason. If I test the code in a separate file, it works as I originally intended.
The code checks to see if a session exists, and if not it creates it and sets it to TRUE. It then performs a second check to see whether or not the session is TRUE, whereupon it is changed to FALSE and the hit stored in the database. This happens ONCE per session.
The code to achieve this is:
<?php
session_start();
// If the session DOES NOT EXIST, make it and set it to TRUE.
if(!isset($_SESSION['new_visit']))
{
$_SESSION['new_visit'] = true;
}
// If the session is TRUE, make it false.
if($_SESSION['new_visit'] == true)
{
$_SESSION['unique_session_id'] = hash("sha512", uniqid("", true) . uniqid("", true) . uniqid("", true));
$_SESSION['new_visit'] = false;
}
echo $_SESSION['unique_session_id'];
When I run this code, as expected, no matter how many times I refresh the page, the output never changes. The 'unique_session_id' variable is always unchanged because each of the if statements are only executed once. However, my production code contains this exact code, but has suddenly stopped working. My production code is this:
<?php
if(empty($article_data))
{
$no_article = true;
}
$options = $this->db->get_options();
$server_options = $this->db->server_options();
// Check site status (on/off).
if($options['status'] == "off")
{
echo $options['offline_message'];
exit(); // Equal to die.
}
if($server_options['force_ssl'] == "on")
{
if($_SERVER["HTTPS"] != "on")
{
header("HTTP/1.1 301 Moved Permanently");
exit(header("Location: https://" . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"]));
}
}
$this->db->store_hit();
$this->db->store_ip();
//----------------------------------------------------------------------------------------------------------
// Store visits (individual sessions). Visits are not unique hits. Visits are the number of unique sessions,
// so a single person may accumulate many visits (sessions), i.e., returning users.
//----------------------------------------------------------------------------------------------------------
// If the session DOES NOT EXIST, make it and set it to TRUE.
if(!isset($_SESSION['new_visit']))
{
$_SESSION['new_visit'] = true;
}
// If the session is TRUE, make it false.
if($_SESSION['new_visit'] == true)
{
$this->db->store_visit();
$_SESSION['unique_session_id'] = hash("sha512", uniqid("", true) . uniqid("", true) . uniqid("", true));
$_SESSION['new_visit'] = false;
}
?><!DOCTYPE html>
<html>
...
</html>
As you can see this code is identical, yet every time I refresh the page the unique_session_id variable changes, which is impossible if the logic is unaffected. My only conclusion is that the session is being deleted or lost between page refreshes.
Notes:
I'm using the MVC pattern which I've written from scratch.
session_start() is being called before any other line of PHP in
index.php.
I've tried moving session_start() to various locations in the file,
including right before the sessions are created. This does nothing.
I've tried using session_write_close(), it does not work.
The 2 logical statements should only ever be executed once per session no matter how many page refreshes take place, and have been working this way for 2-3 months. Why have they suddenly started executing after every single page refresh? What is happening to my session vars that the logic is being evaluated to TRUE every time the page refreshes?
EDIT
The session issue has now been fixed by requesting a new php.ini file from the web host.
Your code works as you wrote
please look at code comments.
if(!isset($_SESSION['new_visit'])) //1st time is not set so enter's to statement
{
$_SESSION['new_visit'] = true; //making $_SESSION['new_visit'] true
}
if($_SESSION['new_visit'] == true) //1st time its true
{
$this->db->store_visit();
$_SESSION['unique_session_id'] = hash("sha512", uniqid("", true) . uniqid("", true) . uniqid("", true));
$_SESSION['new_visit'] = false; //You make it false
}
but when $_SESSION['new_visit'] is false, that mean $_SESSION['new_visit'] is set. now second or more times :
if(!isset($_SESSION['new_visit'])) //variable is set, and it will not enter here
{
$_SESSION['new_visit'] = true; // variable stays false
}
if($_SESSION['new_visit'] == true) //variable is false !!!
{
$this->db->store_visit();
$_SESSION['unique_session_id'] = hash("sha512", uniqid("", true) . uniqid("", true) . uniqid("", true));
$_SESSION['new_visit'] = false;
}
// Finally $_SESSION['unique_session_id'] stays same.
You can use unset($_SESSION['new_visit']); or if it only for this statement or to checking in one page, use variable like $new_visit don't use session for that.
Updated:
Save this specific session handling code in a separate file which you require in the beginning in all of your files.
I noticed that you HAVE TO reload at least once to get a session id, instead you could do this, also simplifying the complexity:
if(!isset($_SESSION['new_visit']))
{
$_SESSION['new_visit'] = true;
$_SESSION['unique_session_id'] = hash("sha512", uniqid("", true) . uniqid("", true) . uniqid("", true));
}
echo $_SESSION['unique_session_id'];
I'm also taking a wild guess that you're not using session_start() properly and in the beginning of ALL files which you ever go into. Once you enter a single page that doesn't have it or is using it incorrectly then things screw up.
Note: You can use
session_destroy();
to delete every set session there is. You can also use
unset($_SESSION['new_visit']);
to unset a certain session.
I am trying to detect if a user on my page has cookies enabled or not. The following code performs the check, but, I have no idea on how to redirect the user to the page they came from.
The script starts a session and checks if it has already checked for cookies. If not, it redirects the user to a test page, and since I had called session_start() in the first page, I should see the PHPSESSID cookie if the user agent has cookies enabled.
The problem is, ths script might be called from any page of my site, and I will have to redirect them back to their selected page, say index.php?page=news&postid=4.
session_start();
// Check if client accepts cookies //
if (!isset($_SESSION['cookies_ok'])) {
if (isset($_GET['cookie_test'])) {
if (!isset($_COOKIE['PHPSESSID'])) {
die('Cookies are disabled');
} else {
$_SESSION['cookies_ok'] = true;
header(-------- - ? ? ? ? ? -------- -);
exit();
}
}
if (!isset($_COOKIE['PHPSESSID'])) {
header('Location: index.php?cookie_test=1');
exit();
}
}
I think its better to make one file set cookie and redirect to another file. Then the next file can check the value and determine if cookie is enabled. See the example.
Create two files, cookiechecker.php and stat.php
// cookiechecker.php
// save the referrer in session. if cookie works we can get back to it later.
session_start();
$_SESSION['page'] = $_SERVER['HTTP_REFERER'];
// setting cookie to test
setcookie('foo', 'bar', time()+3600);
header("location: stat.php");
and
stat.php
<?php if(isset($_COOKIE['foo']) && $_COOKIE['foo']=='bar'):
// cookie is working
session_start();
// get back to our old page
header("location: {$_SESSION['page']}");
else: // show the message ?>
cookie is not working
<? endif; ?>
Load cookiechecker.php in browser it'll tell cookie is working. Call it with command line like curl. It'll say, cookie is not working
Update
Here is a single file solution.
session_start();
if (isset($_GET['check']) && $_GET['check'] == true) {
if (isset($_COOKIE['foo']) && $_COOKIE['foo'] == 'bar') {
// cookie is working
// get back to our old page
header("location: {$_SESSION['page']}");
} else {
// show the message "cookie is not working"
}
} else {
// save the referrer in session. if cookie works we can get back to it later.
$_SESSION['page'] = $_SERVER['HTTP_REFERER'];
// set a cookie to test
setcookie('foo', 'bar', time() + 3600);
// redirecting to the same page to check
header("location: {$_SERVER['PHP_SELF']}?check=true");
}
HTTP_REFERER did not work for me, seems like REQUEST_URI is what I need.
Here is the code I finally used:
session_start();
// ------------------------------- //
// Check if client accepts cookies //
// ------------------------------- //
if( !isset( $_SESSION['cookies_ok'] ) ) {
if( isset( $_GET['cookie_test'] ) ) {
if( !isset( $_COOKIE['PHPSESSID'] ) ) {
die('Cookies are disabled');
}
else {
$_SESSION['cookies_ok'] = true;
$go_to = $_SESSION['cookie_test_caller'];
unset( $_SESSION['cookie_test_caller'] );
header("Location: $go_to");
exit();
}
}
if( !isset( $_COOKIE['PHPSESSID'] ) ){
$_SESSION['cookie_test_caller'] = $_SERVER['REQUEST_URI'];
header('Location: index.php?cookie_test=1');
exit();
}
}
// ------------------------------- //
There's no need to save the original URL and redirect to it afterwards. You can perform a transparent redirect via AJAX which doesn't trigger a page reload. It's very simple to implement. You can check my post here: https://stackoverflow.com/a/18832817/2784322
I think this is easiest solution. Doesn't require separate files and allows you to proceed with script if cookies are enabled:
$cookiesEnabled = true;
if (!isset($_COOKIE['mycookie'])) {
$cookiesEnabled = false;
if (!isset($_GET['cookie_test'])) {
setcookie('mycookie', 1, 0, '/');
#ob_end_clean();
$_SESSION['original_url'] = $_SERVER['REQUEST_URI'];
$uri = $_SERVER['REQUEST_URI'];
$uri = explode('?', $uri);
$q = (isset($uri[1]) && $uri[1])?explode('&', $uri[1]):array();
$q[] = 'cookie_test=1';
$uri[1] = implode('&', $q);
$uri = implode('?', $uri);
header('Location: '.$uri);
die;
}
} else if (isset($_GET['cookie_test'])) {
#ob_end_clean();
$uri = $_SESSION['original_url'];
unset($_SESSION['original_url']);
header('Location: '.$uri);
die;
}
// if (!$cookiesEnabled) ... do what you want if cookies are disabled
I am writing a custom session handler and for the life of me I cannot get a cookie to set in it. I'm not outputting anything to the browser before I set the cookie but it still doesn't work. Its killing me.
The cookie will set if I set it in the script I define and call on the session handler with. If necessary I will post code. Any ideas people?
<?php
/* require the needed classes comment out what is not needed */
require_once("classes/sessionmanager.php");
require_once("classes/template.php");
require_once("classes/database.php");
$title=" "; //titlebar of the web browser
$description=" ";
$keywords=" "; //meta keywords
$menutype="default"; //default or customer, customer is elevated
$pagetitle="dflsfsf "; //title of the webpage
$pagebody=" "; //body of the webpage
$template=template::def_instance();
$database=database::def_instance();
$session=sessionmanager::def_instance();
$session->sessions();
session_start();
?>
and this is the one that actually sets the cookie for the session
function write($session_id,$session_data)
{
$session_id = mysql_real_escape_string($session_id);
$session_data = mysql_real_escape_string(serialize($session_data));
$expires = time() + 3600;
$user_ip = $_SERVER['REMOTE_ADDR'];
$bol = FALSE;
$time = time();
$newsession = FALSE;
$auth = FALSE;
$query = "SELECT * FROM 'sessions' WHERE 'expires' > '$time'";
$sessions_result = $this->query($query);
$newsession = $this->newsession_check($session_id,$sessions_result);
while($sessions_array = mysql_fetch_array($sessions_result) AND $auth = FALSE)
{
$session_array = $this->strip($session_array);
$auth = $this->auth_check($session_array,$session_id);
}
/* this is an authentic session. build queries and update it */
if($auth == TRUE AND $newsession == FALSE)
{
$session_data = mysql_real_escape_string($session_data);
$update_query1 = "UPDATE 'sessions' SET 'user_ip' = '$user_ip' WHERE 'session_id' = '$session_id'";
$update_query2 = "UPDATE 'sessions' SET 'data' = '$session_data' WHERE 'session_id = '$session_id'";
$update_query3 = "UPDATE 'sessions' SET 'expires' = '$expires' WHERE 'session_id' = '$session_id'";
$this->query($update_query1);
$this->query($update_query2);
$this->query($update_query3);
$bol = TRUE;
}
elseif($newsession == TRUE)
{
/* this is a new session, build and create it */
$random_number = $this->obtain_random();
$cookieval = hash("sha512",$random_number);
setcookie("rndn",$cookieval,$expires,'/');
$query = "INSERT INTO sessions VALUES('$session_id','0','$user_ip','$random_number','$session_data','$expires')";
$this->query($query);
//echo $cookieval."this is the cookie <<";
$bol = TRUE;
}
return $bol;
}
code updated. still no luck
for some reason if any html is echoed after the session manager is started the cookie is called after the html. this doesnt make any sense to me
The problem is likely in your if/else statements. You are using:
if($auth = TRUE AND $newsession = FALSE)
...
elseif($newsession = TRUE)
The use of a single = means that you are assigning values, not comparing them. You need to use == instead of =.
Change to this:
if($auth == TRUE AND $newsession == FALSE)
...
elseif($newsession == TRUE)
With the code that you have right now, the first if block of your code will run every time, so your setcookie() call is never reached.
setcookie() returns false if php can't add the header. So for debugging try something like
setcookie("rndn",$cookieval) or die('setcookie failed');
You can combine that with a test whether setcookie() is called in the first place
$rc = setcookie("rndn",$cookieval);
/* DEBUG-code don't forget to remove me */
error_log(sprintf("%s %s\n", date('Y-m-d H:i:s setcookie():'), $rc?'success':'failed'));
(or even better use a debugger like xdebug and e.g. netbeans as frontend).
Did you check the response headers in your browser? E.g. via the firebug extension. Perhaps the client receives the cookie header but doesn't accept it.
According to tour code, at least you have to set / directory in the cookie parameters.
But anyway, first of all you have to sniff cookies from the HTTP log. You can use Firebug to watch if server does set any cookie and if browser send any back