I face some problem on my script that I use PHP and jquery to create login system.
First I have PHP page contain form for login. when user click submit I use jquery to send data to server
$.post('server_login.php', {username:username.val(), password:password.val()}, function(data){
alert(data);
});
in server_login.php I have function to doing login user.
if($_POST['username']=='username' && $_POST['password']=='1234'){
$expire = time() + 60*60*24*30; //1 month expired.
setcookie("user_id", $_POST['username'], $expire);
echo true;
}
and jquery alert "1" on my login page.
the problem is when i refresh my website and retieve cookie, it not show me.
print_r($_COOKIE);
anything wrong?
If the script you are calling is located in another folder on the server (or via url rewrite it appears as if it is under another path), make sure to set the path parameter of the cookie.
By default, setcookie() sets the cookie only for the current path.
If your page is www.domain.com and you make ajax call to www.domain.com/auth/login.php the cookie will be set to /auth and will not be available outside /auth.
So try changing to this:
setcookie("user_id", $_POST['username'], $expire, '/');
I try below code in my script.
Please once try this code if you get cookie value
than something wrong with your code but if this code also
not work than check your browser cookie option enabled or not.
if cookie disabled by browser than also you can't get any cookie
value.
For enabling browser cookie follow below link http://www.blogpatrol.com/enable-cookies.php.
Test Code 1:
$expire = time() + 60*60*24*30; //1 month expired.
setcookie("TestCookie", "shashank patel here", $expire);
print_r($_COOKIE);
Test code 2:
Also check this code with your script this code told you
your browser cookie enabled or not.
error_reporting (E_ALL ^ E_WARNING ^ E_NOTICE);
// Check if cookie has been set or not
if ($_GET['set'] != 'yes')
{
// Set cookie
setcookie ('test', 'test', time() + 60);
// Reload page
header ("Location: test.php?set=yes");
}
else
{
// Check if cookie exists
if (!empty($_COOKIE['test']))
{
echo "Cookies are enabled on your browser";
}
else
{
echo "Cookies are NOT enabled on your browser";
}
}
Related
So I've scoured w3schools and this fine website for some time but I can't figure this out.
I have a script that creates a cookie in the users session upon loading the browser, and another script that will check the value of said cookie and respond with 2 echo's depending on the value.
Script to create the cookie is:
<?php
$cookie_name = "CTF";
$cookie_value = "ChangeThis";
if(!isset($_COOKIE[$cookie_name])) {
setcookie($cookie_name, $cookie_value, time() + 86400, "/", NULL);
}
?>
My IF check for the values is as follows:
<?php
if($_COOKIE[$cookie_value] = "CTF") {
echo "Congratulations. Your token code is 4HeWPzK63Lf5NkGS";
} else {
echo "Your cookie is not set yet.";
}
?>
The code works, and when the cookie is changed to CTF it echo's the correct line. However, when I then delete the cookie and refresh the page, essentially resetting the cookie back to the value of "ChangeThis", the first echo still appears on the page.
Can someone point me in the right direction?
The issue is your if condition. You have used = instead of ==. You are assigning the value instead of comparing. The condition checks if the assignment is successful or not. What you need is the below statement:
if($_COOKIE[$cookie_name] == "CTF")
Also, the cookie value is not "CTF", that's the cookie name, you should compare with the value you are setting it to.
I am new to php, but I have 2 years experience in asp.net. When I am calling logout.php It doesn't doesn't removed the cookie values.
<?php
if (isset($_COOKIE['C_username'])) {
unset($_COOKIE["C_username"]);
unset($_COOKIE["C_password"]);
setcookie("C_username", '', time() - 3600);
setcookie("C_password", '', time() - 3600);
}
echo "<script>alert('".$_COOKIE["C_username"]."');</script>" ; //Here the cookie value is found.
header( 'Location: ../index.php');
?>
After redirecting to another index.php, there also the cookie found.
The cookie is not cleared until the page is reloaded by the browser so if you change your javascript to actually look for the cookie on the browser rather than use the PHP (on server) version of it you may get more predictable results.
Also remember that cookies and header() statements must be run before any other data is sent to the browser so your code should be generating an error anyway as your header() statement is after an echo statement.
So try
<?php
if (isset($_COOKIE['C_username'])) {
setcookie("C_username", '', time() - 3600);
setcookie("C_password", '', time() - 3600);
header( 'Location: ../index.php');
exit;
}
echo '<script>alert(document.cookie);</script>";
?>
Additional Point:
Dont put passwords in cookies There is no need to do this anyway as if you are using it to log the user on when they re-visit, you dont need the password you just set the fact that thay are logged in because you see a cookie, it does not need to have a valid userid/password in that/those cookies.
Also remember that cookies can be turned off by the browser!
I can't figure out why I can't remove a cookie or it's value:
I have simple log in script, when user enters correct login details, this is
setcookie('logged', $admin['username'], time()+60*60*24*365);
Also, session_start() is present on all pages.
When I want to log off a user, the following happens:
if($page=='logoff') {
setcookie('logged', "", time() - 3600);
unset($_COOKIE['logged']); // tried also this
session_destroy();
$_SESSION=null;
header("Location: index.php"); // if this is removed, the code below acts like there's no $_COOKIE['logged'] or it's empty (until refresh)
}
Once it gets redirected to index.php the $_COOKIE['logged'] is back with the old value, like something would set it again (nothing does for sure, I even removed the one and only login cookie set line)
I couldn't find a solution in similar questions. Tested in chrome and IE.
You can't "unset" a cookie. "Expire" it by setting it to a value in the past:
<?php
// set the expiration date to one hour ago
setcookie("logged", "", time() - 3600);
?>
http://www.w3schools.com/php/php_cookies.asp
I have a problem with the cookies.
I have created a simple cookie and tried to echo it on my server.
setcookie('user', 'John', time() + 4800);
echo $_COOKIE['user'];
I also checked the value using the function var_dump() and the result is NULL.
I do not understand why :-(
Note that you cannot set a cookie in PHP and hope to retrieve the cookie immediately in that same script session. It will be available on the next request.
This doesn't mean that the cookie has not been sent, it just means you can't test it in the same script run.
Of course, before that, make sure that your cookies are turned on.
if(!isset($_COOKIE['user'])) {
setcookie('user', 'John', time() + 4800, '/');
// set the cookie with the fourth parameter with root
// so that its sitewide
} else {
echo $_COOKIE['user'];
}
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! :)