Alright I'm totally baffled.
Here's my code:
if ($password == $correct_password[0] && !isset($_COOKIE['user'])) {
setcookie("user", $email, time() + 3600);
var_dump(isset($_COOKIE['user']));
echo "!";
}
So it's doing the var_dumps, meaning that the setcookie should called. But the line right after it (checking if it's set) says it's not set!
If anyone could point out the problem it'd be greatly appreciated. Thanks
$_COOKIE is populated/loaded when the script first starts up, and then is NOT updated by PHP again for the life of the script. Setting a cookie via setcookie will only show up in $_COOKIE on the NEXT execution of the script.
This applies to all of the superglobals, except $_SESSION. They're populated/initalized at script startup and then PHP does not ever touch them again. $_SESSION is populated when you call session_start() (or sessions are set to auto start), which may be done multiple times within a script's lifetime.
PHP is a server-side language.
That means that it can generate whatever it wants and will then pass it to the client.
And that's it.
There is no back and forward on a single request.
1º you instruct the page 'A' to set a cookie
2º client recieves page 'A' and sets the cookie
3º client asks for page 'B' (sending the cookie)
4º server can identify the cookie (only on page 'B')
Page here is used as simple way of understanding a server call.
You can request the same page twice for the purpose.
Still didn't find a solid valid answer, but after endless hours of testing it seems like something with the time. If I set the expiration date too close to the real time, maybe it doesn't register or something. It seemed to work when I set the time further, but I'm taking a break before heavy testing again.
Thanks
When you use setcookie() it will save its value the next time that the HTML is loaded. If you want to see the vardump with the value you just assigned you will need to use $_COOKIE['cookie_name'] = $value;
Related
I am quite confused and would appreciate some help. I have an index.php which starts a session at its very beginning (session_start();). From the browser, I see that a cookie PHPSESSID is created with the id of the session.
However, in the folder /var/lib/php/sessions (the session.save_path), nothing is put.
If I declare any session variables in index.php they are not passed over to other php scripts with session_start() (not even with session_id(the-whatever-PHPSESSID); session_start();).
However, if I call session_start() again, I get the session functioning as I thought it ought (and in the session.save_path I can find a reference to the session id created).
It is quite confusing to me and, perhaps, given by befuddlement, I might not be explaining what happens well. Please let me know if you require any more info!
Here is what I have:
index.php
<?php
session_start();
$_SESSION['sessionid'] = session_id();
$sessionid = "'".$_SESSION['sessionid']."'";
$_SESSION['maxQueries'] = 1883; //11*171 + 2
$_SESSION['cCount'] = 0;
$_SESSION['queries'] = 0;
?>
There is a form there (index.php) which has a captcha key created by a php file (captcha code by Simon Jarvis) which also starts with session_start(). The captcha is generated like this:
(index.php)
<div class="field">
<input type="checkbox" id="human" name="human" onclick="captcha();"/>
<label for="human" class="humancb">I am human</label>
</div>
<div id = "captcha"></div>
(javascript)
if(document.getElementById("human").checked){
document.getElementById("captcha").innerHTML = "<img src='./assets
/php/captcha_code_file.php?rand="+ Math.random() +"' id='captchaimg' >
</img>";}
When I load index.php I see a PHPSESSID - nothing in /var/lib/php/sessions. When I click on the captcha checkbox (and the captcha_code_file.php is invoked) I get the session to work. What am I doing wrong? What am I so terribly missing?
Thank you!
Edit1: I think I managed to pinpoint the issue. As #Hans indicated, the culprit was the $sessionid variable. I was using it to pass it as input to a javascript function when the form was being submitted. Then, I was using the javascript var 'sessionid' in a xhr post request to a php page. All php pages had session_start() in the beginning and their session_id was also passed through javascript. In retrospect, I am not at all sure I can provide an argument as to why I did that, but, anyway, when I omitted that part and the javascript was sending in the xhr post all variables unrelated to the session, the issue seemed to go away. Again, I am not sure I phrase this well and I guess I should start slapping myself on the face a couple of times :D...
Edit2: I would have liked if I could choose BOTH answers as very helpful. This would have reflected the truth. However, Hans, please understand that even though you were closer in a sense (showed the culprit here), it all happened for a completely - or so I think - different reason. That is why I choose Walther's answer. If I could, I would have chosen both.
Thank you both so much for helping!!!!!!
From the official documentation:
Sessions follow a simple workflow. When a session is started, PHP will
either retrieve an existing session using the ID passed (usually from
a session cookie) or if no session is passed it will create a new
session. PHP will populate the $_SESSION superglobal with any session
data after the session has started. When PHP shuts down, it will
automatically take the contents of the $_SESSION superglobal,
serialize it, and send it for storage using the session save handler.
=> saving to a file happens between requests when it's finished executing the current script, not on first session_start call.
http://php.net/manual/en/session.examples.basic.php
$sessionid = $_SESSION['sessionid']; is the correct statement not
$sessionid = "'".$_SESSION['sessionid']."'";
Try this adjustment and see what happens
I am trying to use session_id() on some php pages, but the id changes between every file and it changes everytime i refresh the page. I placed the following script which should increment on ever reload, but it does not.
session_start();
if (!isset($_SESSION['hits'])) $_SESSION['hits'] = 0;
++$_SESSION['hits'];
echo '<p>Session hits: ', $_SESSION['hits'], '</p>';
echo '<p>Refresh the page or click <a href="', $_SERVER['PHP_SELF'],
'">here</a>.';
In my php.ini file, I have cookies turned on as well as set my save_path tp '/tmp'.
In the actual folder, there are session files... so i know it is not a file writing issue. I have also ensured that every file is utf-8 with bom to ensure consistency.
If there are any other solutions you can think of, please help me solve this. It is driving me insane.
Thanks!!!
The 3 possibilities I can think of for your situation are:
How are you calling session_id()? Include that code in your question. If you're calling it with any arguments it will override the session ID to whatever argument you passed.
Are cookies enabled in your browser? The session ID is sent to the browser as a cookie.
Are you calling session_destroy() at any point? This will delete the session data from the server and cause a new session to be started on subsequent pageviews.
That is because you are creating a new session every time you refresh the page. You must enclose your session start statement in a if.
if(session_id() == ''){
session_start();
}
I am facing a difficulty in understanding the usage of cookies in PHP,
Please consider the following code snippet
public function preExecute() {
setcookie("testCookie", "Hello123", time() + 31536000, "/", WebServer::getServerName());
echo "Before Value of cookine in decommission::".$_COOKIE["testCookie"];
setcookie("testCookie", "Hello456", time() + 31536000, "/", WebServer::getServerName());
echo "After Value of cookine in decommission::".$_COOKIE["testCookie"];
}
The output that i am expecting for this code
Before Value of cookine in decommission::Hello123
After Value of cookine in decommission::Hello456
But the output i am getting for the above code snippet is
Before Value of cookine in decommission::Hello456
After Value of cookine in decommission::Hello456
Will appreciate if someone explain me the working, i have gone through resources available in internet, but still i am not clear.
Thanks in advance.
$_COOKIE holds the cookies that have been received in the current request. It is not automatically updated when you call setcookie to set cookies in your response. The cookies you set via setcookie will only appear in $_COOKIE on the next request, when the cookies are sent back to the server.
So what you're seeing is that the second cookie overwrites the first, so only the later value is sent back to the server. I'll guess you have refreshed the page several times already, so you're seeing the cookie. If you clean your cookies and run this again, on the first try you won't see any output, because $_COOKIE is empty and stays empty for the whole request, no matter how often you call setcookie.
If you dont want to change this usage, use sessions. $_SESSION is a global array. You can reach from everywhere (inside class,function) and use instantly (no need to wait next request/page load).
I am trying to setup a session management with cookies in PHP.
My code is as follows:
if(empty($_COOKIE )) {
setcookie('session_id', md5(uniqid()), time()+(EXPIRE CONSTANT));
}
$session_id = isset($_COOKIE['session_id']) ? $_COOKIE['session_id'] : 0;
I will then check session_id for 0 and print an error message if cookies are disabled.
This works fine if cookies are really disabled.
The problem is, if a user clears his history the first time he visits
the site he will get the error message even if cookies are enabled.
Anyone have any clues about this ?
Thank you in advance
When you do the setcookie call, the cookies will be sent when the header is output to the browser. This means the cookie won't be available until the next page load (when the client sends the cookie back to the server). This is mentioned in the php manual for setcookie http://php.net/manual/en/function.setcookie.php:
setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST.
You won't be able to determine if cookies are enabled/disabled until the page has reloaded (from php). I think you'll have to do this check with javascript, or to stay in php do a redirect after setting the cookie for the first time, something like:
if(empty($_COOKIE)) {
if (isset($_GET['cookieset'])) {
// do error message, cookie should be set
}
setcookie('session_id', md5(uniqid()), time()+(EXPIRE CONSTANT));
header('location: http://mysite.com/index.php?cookieset=1');
exit;
}
$session_id = isset($_COOKIE['session_id']) ? $_COOKIE['session_id'] : 0;
#bencoder : I have done the test on iPad and Chrome/PC : you are right for iPad, you do need to refresh the page before you can read the cookie data, but on Chrome/PC, after deleting all cookies, if you set a new one from PHP, you can perfectly get the values directly on the first page load. Why ? There must be a more precise explanation. Why two different behaviors? Does the order of this output/availability of the data depend on the browser request to the server? Interesting to know...
I am trying to implement a login system with a 'remember me' feature . This is my my login page: http://pastebin.com/q6iK0Mgy . In this I am trying to extend the session cookie(PHPSESSIONID) expiration using session_set_cookie_params() . But its not working.
Relevant portion from the code: In this the inner if() loop is being executed , but session_set_cookie_params('3600') is having no effect. I am calling session_name() , as it is supposed to be a requirement for session_set_cookie_params() (according to one of the comments on php manual)
if ( isset($_POST["submit"]) )
{
session_name() ;
echo "calling before checked " ;
if ( $_POST["remember"] == "on")
{
// extend expiration date of cookie
session_set_cookie_params('3600');
echo "<br/>calling after sessions_set_cookie_params" ;
}
}
require_once("includes/session.php"); //session start ?>
I hope I was able to explain what I want to do. Basically what I a trying to do is extend the session_cookie's expiration. is my way of doing completely wrong? is there another way to achieve the same ?
thanks
Never too old for an answer right?
So, PHP is dumb. As in, it doesn't do what you think would make sense.
session_set_cookie_param will not do anything until the exact moment that you call session_start. So if you set cookie params after calling session start, too late. If you set the cookie params but then don't call session_start, nothing happens.
session_start is also a funny beast. It only reads cookie data the first time it is called -well that is unless.... you force it to write, or there is no cookie to begin with. So if there is no cookie, it writes the cookie data and the client saves your session. yay! But when the cookie exists already, how to we force it to write, and therefore update our new expiry date??
So, we have this odd effect of ignoring all of your session_set_cookie_param calls if a cookie already exists on the client. Even better, if you explicitly call setcookie(session_name(),blah blah blah), php will STILL not emit the cookie.
So, let's force php to emit a cookie.
option 1
This works by calling session_id with the only value that won't clobber your existing session. Documentation at http://php.net/session_id states that
Note: When using session cookies, specifying an id for session_id() will always send a new cookie when session_start() is called, regardless if the current session id is identical to the one being set.
session_id($_COOKIE[session_name()]);
So anyways it's 6 in the morning and I haven't slept yet and you probably figured this out months if not years ago, but what the hell, maybe i'll save someone else the 2 or 3 hours of my life i'll never get back. ha ha.
From the documentation:
You need to call
session_set_cookie_params() for every
request and before session_start() is
called.
Also check http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-lifetime