I am trying the Post-Redirect-Get pattern.
Here are my custom functions
<?php
function ReadCookieMessage()
{
if (($_COOKIE["c"]) && ($_COOKIE["t"]))
{
$message = $_COOKIE["t"];
$message = htmlspecialchars($message);
if ($_COOKIE["c"] == "r")
{
$cssclass = 'error_msg';
}
else if ($_COOKIE["c"] == "g")
{
$cssclass = 'success_msg';
}
setcookie("c", "", time()-3600);
setcookie("t", "", time()-3600);
return '<div class="' . $cssclass . '">' . $message .'</div>';
}
}
?>
<?php
function SetCookieMessage($c,$t)
{
setcookie("c",$c, time()+3600);
setcookie("t",$t, time()+3600);
}
?>
I do SetCookieMessage("g","Your password has been changed, you may now login again"); on my change password page.
Then i do
echo ReadCookieMessage();
on my login page. I am not sure whats up. setcookie works when i set the r cookie if they check remember when they login. I also tired
setcookie("c","g", time()+3600);
setcookie("t","Your password has been changed, you may now login again", time()+3600);
in replacement for the SetCookieMessage function.
Not sure if
if ($SqlChangePass)
{
session_unset();
session_destroy();
setcookie("r", "", time()-3600);
SetCookieMessage("g","Your password has been changed, you may now login again");
header("Location: /login");
}
will be any helpful to you. Its in the changepassword script.
Php isn't giving me any errors. The goal of the functions is to set a message color(r means red and g means green) and text. Then take them to another page and read the message. The page it goes to isn't showing any sort of a message.
so if I get it right you execute as follows:
<?php
SetCookieMessage("something","here");
ReadCookieMessage();
?>
If this is the case, that would be normal behaviour.
Cookies are sent along with the result page in the page headers.
So you would only be able to read cookies on a next request.
e.g. First Request:
Do stuff
Place Cookie
Return result page
Second request could be:
Do stuff
Read cookie
return result page
You can read more about cookies on Wikipedia: Wikipedia page about HTTP Cookies
I quote:
The cookie is sent as a field in the header of the HTTP response by a web server to a web browser and then sent back unchanged by the browser each time it accesses that server.
I hope I understood your question correctly. And that my answer helps.
"I put SetCookieMessage("g","Your password has been changed, you may now login again"); echo ReadCookieMessage(); on a test page."
As Bart said, you can't set a cookie and check it on the same page.
"If i load the page, i see nothing. If i refresh the page again, i see a message. If i refresh again, i don't see the message"
On you case, that's what is happening:
You set the cookie, they're correctly set. After you set the cookie, you try to check it, but the script will not be able to see it because it was not set when it started
You reload the page, the script can now read the cookie and will display your message. But in your code, you tell the browser to expiry the cookies on ReadCookieMessage() when you set it into the past (-3600).
You reload the page, and set the cookies again and it start all over because the previous cookie has now been unset.
Check the link Bart provided! :)
Related
I think I'm making an awkward mistake here but I really fail to find it. I've used browser developer tools and watched each step closely. This is the code and I want the number of visits to get reset after the Restart link is pressed, but it just keeps incrementing:
//test.php:
<?php
if(isset($_COOKIE['visits']) && isset($_GET['restart'])){
if($_GET['restart']=='true') {
setcookie('visits',null,time()-24*3600*365,'/');
unset($_COOKIE['visits']);
header("Location: test.php");
exit;
}
}
if(!isset($_COOKIE['visits'])){
$visits = 1;
setcookie('visits',$visits,time()+24*3600*365);
echo "Welcome To This Website";
}
else{
$visits = $_COOKIE['visits']+1;
setcookie('visits',$visits,time()+24*3600*365);
echo "You've visited this website ".$_COOKIE['visits']. ' times before.<br>';
echo "<a href='?restart=true'>Restart</a><br>";
}
The final guess I've come up with right now is that when using a redirect header, the browser does the redirection request before setting the received cookies, I'm not sure though. Otherwise, I can't think of anything else that may cause this behavior. Anyone could please comment on this and make it clear?
In your code it looks like the header is sent and the user is redirected before the cookie is set. You could try output buffering and echo a dot echo "."; directly before the header(... line to ensure some communication with the client before they are redirected.
Edit: My understanding of what is happening here is that the cookie and redirect headers are being sent simultaneously, but in some server/client combinations the redirect is occurring before the browser has a chance to set the cookie. Pushing some content to the browser along with the headers gives it a chance to process the cookie, but you must obviously enable output buffering in your php.ini or use ob_start() and ob_end_flush() before and after the header setting and echoing.
I know that with sessions in php, a cookie that stores the session ID is set on the client's side. The client can turn off these cookies, which I presumes makes sessions not work. How can I detect if the client has disabled the session cookies?
You can use javascript navigator.cookieEnabled. This returns true or false.
So
if(navigator.cookieEnabled)
//do something
else
//do something else
assuming you started a session on a previous page...
<?php
if(session_status() == PHP_SESSION_ACTIVE)
{
echo 'cookies & sessions enabled';
}
else
{
echo 'no cookies or sessions';
}
?>
or you're looking for a non-session cookies as well.
<?php
if(!empty($_COOKIE))
{
echo 'cookies are tasty';
}
else
{
echo 'no cookies to eat';
}
?>
with a pure php solution you can't check if sessions/cookies are enabled without setting a cookie on a previous page
If you know you MUST use a session, the usual approach is to redirect the user instantly at the start while trying to set a cookie, and then complain about the cookie not being set on the second page.
User goes to http://www.example.com
System sets a cookie (maybe only starts the session, maybe a dedicated test cookie).
System redirects to http://www.example.com/?cookietest=true
On that page, if the cookie is not sent back, complain to the user.
On the other hand, most of the time a session really is not needed if you do not have to log someone in. And IF you do, most users will understand they need to allow cookies, because otherwise the login will fail.
I have a log in form that allows persistent login and regular session. Long story made short, when users are in their account, they can change password, email and stuff. But for that, I need to get their username from their session or cookie first (so I can do the proper SQL query).
I try to do so with this code:
if(isset($_SESSION['username']))
{
$username = $_SESSION['username'];
}
else
if(isset($_COOKIE['username']))
{
$username = $_COOKIE['username'];
}
But if I try to echo $username, I keep getting "undefined variable". Why is that?
I noticed that if I put a session_start(); at the top. I get the proper username for session but not for cookie of course. How can I solve that?
The weird part (for me) is that I got the exact same code (well that part) in another page and username isn't undefined.
PS: If something isn't clear or more information is needed, please tell me.
EDIT
I tried this:
function accountValidation()
{
if(isset($_SESSION['username']))
{
$username = $_SESSION['username'];
}
else if(isset($_COOKIE['username']))
{
$cookie = $_COOKIE['username'];
$explode = explode(' - ', $cookie);
$username = $explode['0'];
}
echo $username;
}
accountValidation();
And it worked ... So if I put it into a function and then call it, it works?! What is the diference? Why does it need to be into a function for it to work???
If you set certain cookie, it would be available to you from next reload. As $_COOKIE is set when a page head is called. You wont be able to retrieve the cookie from the same page which has set the cookie. I hope you got what i meant. If not let me know I would give an better example.
EDIT:
Example
<?php
session_start();
$_SESSION['test'] = 'test1success';
echo $_SESSION['test'];// would display test1success
if (!isset($_COOKIE['test2']))
{
setcookie("test2", "test2success", time()+3600);
}
echo $_COOKIE['test2'];
// wont display test2success when you load the page for first time
// reload it & it would display test2success
?>
Explanation:
The first thing you need to understand is that the cookie is stored on your PC(browser) when the page is loaded. The client (i.e. browser) sends cookie headers to the server & does the page execution. The values set by set_cookie during page execution are set on the client pc, and the server doesn't know about the new values just set - unless you reload the page & the cookie header is sent back.
I am a beginner for PHP and studying to use cookie for login. Would any body please check my code to see what is my problem, or let me how to fix this problem.
When I open the page at the first time, the cookie will not work. It will work when I repeated to open that link. However, I still could not make it work after I use function include and header One of codes is :
One code cookie.php is :
<?php
setcookie("cookiename",$_REQUEST['name']);
if(isset($_COOKIE['cookiename'])){
$cookieSet = ' The Cookie is ' . $_COOKIE['cookiename'];
} else {
$cookieset = ' No Cookie has been set';
}
setcookie("cookiepwd",$_REQUEST['pwd']);
print_r($_COOKIE);
?>
When I run this code first time, it will does not show any thing. I can see cookie data at second time. From some website it is said that cookie would not be read at the same page.
So I moved print_r($_COOKIE) to second php file as well as added function include() or header() to above file, but both neither works.
Cookie2.php:
<?php
setcookie("cookiename",$_REQUEST['name']);
if(isset($_COOKIE['cookiename'])){
$cookieSet = ' The Cookie is ' . $_COOKIE['cookiename'];
} else {
$cookieset = ' No Cookie has been set';
}
setcookie("cookiepwd",$_REQUEST['pwd']);
include(‘printcookie.php’);
//or header("Location: printcookie.php")
?>
printcookie.php:
<?php
print_r($_COOKIE);
?>
Thank you very much for answering in advance!
Michelle
setcookie only sets up the header, that is being sent to the client. It doesn't change the $_COOKIE superglobal.
In other hand - $_COOKIE is filled up with the cookies sent from the client
So at first step - you set the cookie with setcookie and have nothing in $_COOKIE because client hasn't sent it yet, and will only on the next request.
And there is no way of doing what you want, rather than modifying $_COOKIE manually
PS: it is a bad idea to put user's password in the cookie
Give zerkms the answer, but I just want to reiterate:
Cookies are not bad for storing bits of info like the user's theme preferences or preferred start page, etc. They get their bad rep from being used for identity and authentication handling. There are cookies out there that basically have "isAdmin=0" in order to control user access. It is very easy to change that to isAdmin=1 and have a field day. Since you are new to PHP, take the time to learn about sessions now while it's all new to you.
When you set a cookie using setcookie, you are sending an HTTP header to the browser with the cookie info. The browser will then pass back that cookie in any future requests to the server. The $_COOKIE global variable holds the cookie info passed in from the browser to the server.
Since you are using $_REQUEST to get the cookie name, you don't need to check the cookie (otherwise you wouldn't have the data to set it right?). So consider going this route:
if(!isset($_COOKIE['cookiename'])) {
$name = $_POST['name']);
setcookie("cookiename",$name);
} else {
$name = $_COOKIE['cookiename']);
}
echo "Welcome back $name!";
This will also help out if they clear cookies, etc.
But really, the safer route is:
session_start();
if(!isset($_SESSION['name'])){
$_SESSION['name'] = $_POST['name']);
}
if(!isset($_SESSION['pwd'])){
$_SESSION['pwd'] = $_POST['pwd']);
}
$name = $_SESSION['name'];
$pwd = $_SESSION['pwd'];
And even this would be frowned upon for serious web security, where you should simply check the password against a stored hash and then delete it, using other global variables to confirm session integrity. But there's now a whole StackExchange for that.
As a workaround you could use location() after checking the cookie to have access to the stored data.
But be aware that location() fails, if anything (including breaks and blanks in your script) already sent to the browser.
I have a login that I've implemented with AJAX and the PHP on the backend sets $_SESSION['guest'] before sending the response text back. Then it the javascript on the front end redirects me to the guest page which checks whether or not isset($_SESSION['guest']), but often this results in false, and i'm taken to another page (using my else branch).
I'm wondering if maybe I'm checking for it too early and that's why isset($_SESSION['guest']) results in false. But I make it count down 5 seconds before redirecting to the page that tests for it, so this is what I don't understand.
After it happens a couple of times (i logout and log back in again), it stops failing and I can't get it to fail which obviously doesn't help! Thought that may be a caching/cookie problem but I've cleared all that and it still won't fail again.
Any ideas?
//this is the login script snippet
if($rows == 1){
$_SESSION[$type] = $username; //$type is posted over as guest or client. this is valid right?
$_SESSION[$type.'_id'] = $result['id'];
echo $_SESSION['welcome'] = 'You have logged in successfully.';
}
<?php
//snippet from the guest page. session_start() is invoked within the included 'page_top.php'
include('page_top.php');
if(isset($_SESSION['guest'])){
if(isset($_GET['sect'])){
if($_GET['sect'] == 'photography'){
include('view_album.php');
}
else{
include('404.html');
}
}
else{
include('welcome.php');
}
}
else{
include('403.html'); //i get redirected here!
}
include('page_bottom.php');
?>
edit: i now think that when it fails the session variable just isn't getting set because if i reload my guest page, it results in the 403.html page every time, so it's not a delay, it just doesnt get set.
I don't think you should be echo-ing a variable as you are setting it? That doesn't make any sense to me.
echo $_SESSION['welcome'] = 'You have logged in successfully.';
If $type is being posted over as guest or client, shouldn't it be $_SESSION[$_POST['type']];
or are you setting $type to the POST variable somewhere else in the page?
You must include this at the top of the page (before ANY HTML or whitepace output, and after the < ?php):
session_start();
EDIT:
I know this is an old post. But for anyone that needs it in the future here it is!