I am new to zend framework. I have write this code to set cookie in my website.
public function setCookie($data){
$email_cookie = new Zend_Http_Cookie('user_email_id', $data['user_email_id'], $_SERVER['HTTP_HOST'], '', FALSE);
$pass_cookie = new Zend_Http_Cookie('user_password', $data['user_password'], $_SERVER['HTTP_HOST'], '', FALSE);
$cookie_jar = new Zend_Http_CookieJar();
$cookie_jar->addCookie($email_cookie);
$cookie_jar->addCookie($pass_cookie);
}
I dont even know by writing this code, my cookie is set or not?
now If I want to retrieve the cookie then how can I do it?
Zend_Http_Cookie is not for setting cookies. It is a class used by Zend_Http_Client for sending and receiving data from sites that require cookies. To set cookies just use the standard PHP setcookie() function:
setcookie('user_email_id', $data['user_email_id'], time() + 3600, '/');
setcookie('user_password', $data['user_password'], time() + 3600, '/');
this will set cookies that expire in 1 hour. You can then access these on subsequent requests using $_COOKIE['user_email_id'] and $_COOKIE['user_password']; or if you are using ZF's MVC classes: $this->getRequest()->getCookie('user_email_id') (from a controller method).
Your cookies are set by sending response. You can modify response in your code.
$cookie = new Zend_Http_Header_SetCookie();
$cookie->setName('foo')
->setValue('bar')
->setDomain('example.com')
->setPath('/')
->setHttponly(true);
$this->getResponse()->setRawHeader($cookie);
By default, the front controller sends response when it has finished dispatching the request; typically you will never need to call it.
http://framework.zend.com/manual/1.12/en/zend.controller.response.html
Check Zend_Http_Cookie
You will get your cookie like following:
echo $email_cookie->getName(); // user_email_id
echo $email_cookie->getValue(); // Your cookie value
echo ($email_cookie->isExpired() ? 'Yes' : 'No'); // Check coookie is expired or not
Use this way you can do it
in your controller do it code as
$cookie = new Zend_Http_Cookie('cookiename',
'cookievalue',
time() + 7200 //expires after 2 hrs
);
echo $cookie->__toString();
echo $cookie->getName(); //cookie name
echo $cookie->getValue(); //cookie value
Try:
$ret_as = COOKIE_STRING_ARRAY;
Zend_Http_CookieJar->getAllCookies($ret_as);
//Get all cookies from the jar. $ret_as specifies the return type
//as described above. If not specified, $ret_type defaults to COOKIE_OBJECT.
Ref: Zend Cookies
Related
I am working on WordPress multisite, and I have changed the login functionality. However, it needs the users to delete old cookies before using this functionality I have created. So I am trying to clear the user's cookies by setting a new cookie, custom_wordpress_login_cookie, to know which of the users have old cookies in the browser, as shown in the following code.
add_action('init', 'clear_all_cookies_before_login');
function clear_all_cookies_before_login(){
if( ! isset( $_COOKIE['custom_wordpress_login_cookie'] ) ){
foreach( $_COOKIE as $key => $value ){
setcookie( $key, '', time() - YEAR_IN_SECONDS);
}
setcookie( 'custom_wordpress_login_cookie', 'true',
time() + YEAR_IN_SECONDS, '/', COOKIE_DOMAIN, false, true );
}
}
The new cookie is being set, but the old cookies persist. What could be the issue?
To prevent creation of a second cookie with the same name, pass / as the path argument to setcookie().
And so, you must change this line:
setcookie( $key, '', time() - YEAR_IN_SECONDS);
to:
setcookie( $key, '', time() - YEAR_IN_SECONDS, '/');
Also note that the way you're expiring cookies may not work if the user's system time is configured incorrectly. This is rare*, but does happen. A simpler way to expire cookies is to simply call:
setcookie( $key, '', 1, '/');
*the user would likely run into TLS issues if the webpage is served over HTTPS.
This is not an answer related to how you can clear cookies, but this solution will help you make sure that all the users currently logged into your website will need to login again.
Go in the wp-config.php and reset the secret salt keys. You can generate new ones here: https://api.wordpress.org/secret-key/1.1/salt/ .
That way it will force all of your users to login again and you no longer need to write code to delete the users' cookies.
Try: setcookie( $key, '', time() - 3600, '/', COOKIE_DOMAIN);
According WordPress documentation, it combines the salt keys with the password. The hash function mixes these up and gives a result. After that it stores inside a cookie to "remember" the login process or tracking behavior.
example: That's the reason two different usernames with the same password are successfully identified as different logins.
First you have to make distinct cookies for every user. Let's say custom_wordpress_login_cookie will contain inside a string with the username or any associated encoded string (preferred).
Then you will check if the custom_wordpress_login_cookie exists and contains the appropriate username.
Act accordingly, if found, perform your logic and then delete (unset) the cookie. Else create a new one.
The following code explains the flow...
function clear_all_cookies_before_login() {
// Current Time of visit
$time_now = date('F j, Y g:i a');
// Check a cookie already set
if(isset($_COOKIE['custom_wordpress_login_cookie'])) {
// Found Cookie
function check_visitor() {
// Retrieve information to use for your logic
$lastvisit = $_COOKIE['custom_wordpress_login_cookie'];
$string .= 'Since your last login '. $lastvisit .'. We have a tone of new things!';
// Delete the old cookie so that we can set it again with updated time
unset($_COOKIE['custom_wordpress_login_cookie']);
return $string;
}} else {
// Not found cookie
function check_visitor() {
$string .= 'Welcome to our website! Please login...' ;
return $string;
}
}
add_shortcode('New_Message', 'check_visitor');
// Set new cookie with expiration of 1 Day
setcookie('custom_wordpress_login_cookie', $time_now , time()+86400);
}
you must used first unset
unset( $_COOKIE[$v_username] );
setcookie( $v_username, '', time() - ( 15 * 60 ) );
Once that’s done, we will force the cookie to expire by setting its value variable to a null value (“”) and passing in a timestamp that’s in the past (time() - ( 15 * 60 )).
You are doing absolutely correct but the deletion of the cookie would not work. The above code will only expire the cookie in the current session. You have to destroy the session also if you want to make the old cookie dis-appear. Thus your new code would be like this:
add_action('init', 'clear_all_cookies_before_login');
function clear_all_cookies_before_login(){
if( ! isset( $_COOKIE['custom_wordpress_login_cookie'] ) ){
foreach( $_COOKIE as $key => $value ){
setcookie( $key, '', time() - YEAR_IN_SECONDS);
}
setcookie( 'custom_wordpress_login_cookie', 'true', time() + YEAR_IN_SECONDS, '/', COOKIE_DOMAIN, false, true );
//Destroy the session and re-direct the user to other location
//this will make sure to disappear the old cookie and new cookie
//only will remain
session_destroy();
header("Location:/");
}
}
I need to figure out how to unset this cookie. Everything I tried so far has failed.
This is how I am currently unsetting it and it doesn't seem to work.
setcookie("user_id", $user_id, time() - 7200);
This is how I set it:
setcookie("user_id", $user_id, time() + 7200);
I have this function called set_session_from_cookie() that checks if a cookie is set, and if it is set, it starts a new session using the cookie.
The problem is that when I use this on my page I am unable to logout. I assume this is because I am unable to unset the session.
The reason I have this function is if a user wants to be remembered after they end the session, they can restart the session by calling the cookie.
function set_session_from_cookie()
{
if (isset($_SESSION['user_id'])) {
echo '';
} else {
$_SESSION['user_id']=$_COOKIE['user_id'];
}
}
Logout:
<?php
require'core.php';
session_destroy();
setcookie("user_id", "", time() - 7200);
header('Location:/social_learning/site_pages/starter-template.php');
I set my cookie with the following code:
if ($rememberme == "on") {
$user_id = mysql_result($query_run, 0, 'id');
setcookie("user_id", $user_id, time() + 7200);
$_SESSION['user_id'] = $user_id;
redirect('home_page.php');
} else {
if ($rememberme == "") {
echo 'ok';
$user_id = mysql_result($query_run, 0, 'id');
echo $user_id;
$_SESSION['user_id'] = $user_id;
redirect('home_page.php');
}
}
How can I restart the session using the saved cookie without using the function I created? Since the function seems to be causing the user to no longer be able to logout.
Set the cookie's expiration date to a time in the past (like one second after epoch, for example).
setcookie("yourCookie", "yourValue", 1);
This will cause the cookie to expire.
1 is used instead of 0, because 0 sets the cookie to expire at the end of the session.
The solution to this problem was that the I needed to set the correct path to unset the cookie since I was unsetting it from a different file that I originally set it in.
I found out which path I needed to use for the unset by looking for the cookie inside my browser cookies, and once I found the cookie inside my browser, the path was listed near the cookie. So I then set the path to the cookie like so:
setcookie("user_id", $user_id, time() - 1, "/social_learning/site_pages");
The last parameter is the path. And it worked.
My original setcookie looks like this:
setcookie("user_id", $user_id, time() + 7200, "");
There are few security concerns regarding you code, however to answer your question, to unset a cookie in php, all you need to do is to set expiration time to a time in the past:
setcookie("user_id", "", time()-10, "/");
"loginform.php" is not a valid domain, that might be the problem here.
Look at the php manual for information on setcookie
http://php.net/manual/en/function.setcookie.php
These notes should explain the process:
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Cookies must be deleted with the same parameters as they were set
with. If the value argument is an empty string, or FALSE, and all
other arguments match a previous call to setcookie, then the cookie
with the specified name will be deleted from the remote client. This
is internally achieved by setting value to 'deleted' and expiration
time to one year in past.
Because setting a cookie with a value of FALSE will try to delete the
cookie, you should not use boolean values. Instead, use 0 for FALSE
and 1 for TRUE.
use this code
setcookie("CookieName", "", time()-(60*60*24), "/");
works everytime for me in every website
In php manual, you can delete a cookie by setting a expiration date is in the past:
setcookie("key","",time()-3600);
In some case, you should provide path and domain for arguments.
In fact, if you assign a cookie with a empty string, it'll also be unset:
setcookie("key","");
Though after reading explanations about setting cookie and not working for first time i find it difficult to resolve the below problem as am new to php and cookies.
I have a webpage with for (e.g) cp.php, login.php, header.php, maindata.php , bottom.php. Whenever i login to the webpage cp.php will be processed from there 1.header.php will be called first 2.maindata.php will be called and 3.bottom.php will be called.
So am setting my cookie at maindata.php and the code is like,
<?php
$cid = $_GET["id"];
$XmlPath = $_GET["path"];
$numpath = $_GET["numpath"];
$finepath =$_GET["finepath"];
$Tech =$_GET["tech"];
$read_str="";
function read($Path)
{
$temp="";
if(file_exists($Path))
{
$library = new SimpleXMLElement($Path,null,true);
foreach($library->children("SAS") as $info){
foreach($info->children("SAS") as $attributes){
$nameVal = $attributes->Name."=".$attributes->Value;
$str_temp .=$nameVal."#";
}
}
}else
{
$str_temp ="NA";
}
return $str_temp;
}
$arrpath =explode(",",$XmlPath);
/*Reading and storing arrpath[0] has the path of xml to be parsed*/
$strG=read($arrpath[0]);
$strC=read($arrpath[1]);
$strB =read($arrpath[2]);
setcookie($cid.'strE',$strG);
setcookie($cid.'comstr',$strC);
setcookie($cid.'basstr',$strB);
(....)
in the same file am reading the cookie using the below code,
$read_str =$_COOKIE[$cid.'strE'].$_COOKIE[$cid.'comstr'].$_COOKIE[$cid.'basstr'];
after this process is done bottom.php will be called and for the first time loading is completed.As i said for the first time am not getting any value in $read_str, but if i refresh the page and do all the process again i am getting the value.
As SETCOOKIE will return TRUE incase of successfully setting cookie i tried putting it in an if-loop and it returned false even for the first time.
kindly assist me in finding where the problem exists!
Make use of isset to check if a cookie exists and then try setting one.
Something like this.
if(!isset($_COOKIE['yourcookie'])) {
setcookie('yourcookie', 'Some data !');
$_COOKIE['yourcookie'] = 'Some data !';
}
echo $_COOKIE['yourcookie'];
I arrived here looking for an answer as well. Here's the deal.
When you set a cookie it can only be accessed on the next page load, that is why you can't access it after you set it. If you really need to work with the cookie data right away, you could set the value directly in global cookie such as:
$_COOKIE['my_cookie'] = 'i am a cookie';
Use setcookie()just the same so you can set expiration, domain, etc..
I need to figure out how to unset this cookie. Everything I tried so far has failed.
This is how I am currently unsetting it and it doesn't seem to work.
setcookie("user_id", $user_id, time() - 7200);
This is how I set it:
setcookie("user_id", $user_id, time() + 7200);
I have this function called set_session_from_cookie() that checks if a cookie is set, and if it is set, it starts a new session using the cookie.
The problem is that when I use this on my page I am unable to logout. I assume this is because I am unable to unset the session.
The reason I have this function is if a user wants to be remembered after they end the session, they can restart the session by calling the cookie.
function set_session_from_cookie()
{
if (isset($_SESSION['user_id'])) {
echo '';
} else {
$_SESSION['user_id']=$_COOKIE['user_id'];
}
}
Logout:
<?php
require'core.php';
session_destroy();
setcookie("user_id", "", time() - 7200);
header('Location:/social_learning/site_pages/starter-template.php');
I set my cookie with the following code:
if ($rememberme == "on") {
$user_id = mysql_result($query_run, 0, 'id');
setcookie("user_id", $user_id, time() + 7200);
$_SESSION['user_id'] = $user_id;
redirect('home_page.php');
} else {
if ($rememberme == "") {
echo 'ok';
$user_id = mysql_result($query_run, 0, 'id');
echo $user_id;
$_SESSION['user_id'] = $user_id;
redirect('home_page.php');
}
}
How can I restart the session using the saved cookie without using the function I created? Since the function seems to be causing the user to no longer be able to logout.
Set the cookie's expiration date to a time in the past (like one second after epoch, for example).
setcookie("yourCookie", "yourValue", 1);
This will cause the cookie to expire.
1 is used instead of 0, because 0 sets the cookie to expire at the end of the session.
The solution to this problem was that the I needed to set the correct path to unset the cookie since I was unsetting it from a different file that I originally set it in.
I found out which path I needed to use for the unset by looking for the cookie inside my browser cookies, and once I found the cookie inside my browser, the path was listed near the cookie. So I then set the path to the cookie like so:
setcookie("user_id", $user_id, time() - 1, "/social_learning/site_pages");
The last parameter is the path. And it worked.
My original setcookie looks like this:
setcookie("user_id", $user_id, time() + 7200, "");
There are few security concerns regarding you code, however to answer your question, to unset a cookie in php, all you need to do is to set expiration time to a time in the past:
setcookie("user_id", "", time()-10, "/");
"loginform.php" is not a valid domain, that might be the problem here.
Look at the php manual for information on setcookie
http://php.net/manual/en/function.setcookie.php
These notes should explain the process:
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Cookies must be deleted with the same parameters as they were set
with. If the value argument is an empty string, or FALSE, and all
other arguments match a previous call to setcookie, then the cookie
with the specified name will be deleted from the remote client. This
is internally achieved by setting value to 'deleted' and expiration
time to one year in past.
Because setting a cookie with a value of FALSE will try to delete the
cookie, you should not use boolean values. Instead, use 0 for FALSE
and 1 for TRUE.
use this code
setcookie("CookieName", "", time()-(60*60*24), "/");
works everytime for me in every website
In php manual, you can delete a cookie by setting a expiration date is in the past:
setcookie("key","",time()-3600);
In some case, you should provide path and domain for arguments.
In fact, if you assign a cookie with a empty string, it'll also be unset:
setcookie("key","");
When I create a cookie, how to get cookie's expire time?
Putting an encoded json inside the cookie is my favorite method, to get properly formated data out of a cookie.
Try that:
$expiry = time() + 12345;
$data = (object) array( "value1" => "just for fun", "value2" => "i'll save whatever I want here" );
$cookieData = (object) array( "data" => $data, "expiry" => $expiry );
setcookie( "cookiename", json_encode( $cookieData ), $expiry );
then when you get your cookie next time:
$cookie = json_decode( $_COOKIE[ "cookiename" ] );
you can simply extract the expiry time, which was inserted as data inside the cookie itself..
$expiry = $cookie->expiry;
and additionally the data which will come out as a usable object :)
$data = $cookie->data;
$value1 = $cookie->data->value1;
etc. I find that to be a much neater way to use cookies, because you can nest as many small objects within other objects as you wish!
This is difficult to achieve, but the cookie expiration date can be set in another cookie. This cookie can then be read later to get the expiration date. Maybe there is a better way, but this is one of the methods to solve your problem.
You can set your cookie value containing expiry and get your expiry from cookie value.
// set
$expiry = time()+3600;
setcookie("mycookie", "mycookievalue|$expiry", $expiry);
// get
if (isset($_COOKIE["mycookie"])) {
list($value, $expiry) = explode("|", $_COOKIE["mycookie"]);
}
// Remember, some two-way encryption would be more secure in this case. See: https://github.com/qeremy/Cryptee
When you create a cookie via PHP die Default Value is 0, from the manual:
If set to 0, or omitted, the cookie
will expire at the end of the session
(when the browser closes)
Otherwise you can set the cookies lifetime in seconds as the third parameter:
http://www.php.net/manual/en/function.setcookie.php
But if you mean to get the remaining lifetime of an already existing cookie, i fear that, is not possible (at least not in a direct way).
It seems there's a list of all cookies sent to browser in array returned by php's headers_list() which among other data returns "Set-Cookie" elements as follows:
Set-Cookie: cooke_name=cookie_value; expires=expiration_time; Max-Age=age; path=path; domain=domain
This way you can also get deleted ones since their value is deleted:
Set-Cookie: cooke_name=deleted; expires=expiration_time; Max-Age=age; path=path; domain=domain
From there on it's easy to retrieve expiration time or age for particular cookie. Keep in mind though that this array is probably available only AFTER actual call to setcookie() has been made so it's valid for script that has already finished it's job. I haven't tested this in some other way(s) since this worked just fine for me.
This is rather old topic and I'm not sure if this is valid for all php builds but I thought it might be helpfull.
For more info see:
https://www.php.net/manual/en/function.headers-list.php
https://www.php.net/manual/en/function.headers-sent.php
To get cookies expire time, use this simple method.
<?php
//#############PART 1#############
//expiration time (a*b*c*d) <- change D corresponding to number of days for cookie expiration
$time = time()+(60*60*24*365);
$timeMemo = (string)$time;
//sets cookie with expiration time defined above
setcookie("testCookie", "" . $timeMemo . "", $time);
//#############PART 2#############
//this function will convert seconds to days.
function secToDays($sec){
return ($sec / 60 / 60 / 24);
}
//checks if cookie is set and prints out expiration time in days
if(isset($_COOKIE['testCookie'])){
echo "Cookie is set<br />";
if(round(secToDays((intval($_COOKIE['testCookie']) - time())),1) < 1){
echo "Cookie will expire today.";
}else{
echo "Cookie will expire in " . round(secToDays((intval($_COOKIE['testCookie']) - time())),1) . " day(s)";
}
}else{
echo "not set...";
}
?>
You need to keep Part 1 and Part 2 in different files, otherwise you will get the same expire date everytime.