I have a question about cookies in cakephp. I create a cookies in cakephp view successfully, and I wrote a javascript function to delete that cookies if the page reloads, and that function is successfully deleted.
But after that cookies deleted, the same cookies cannot create anymore. Why does this happen?
This is my code that I have used to create that cookies :
$isiCookies=$awb['Awb']['id'].'^'.$awb['Awb']['awb_number'].'^'.$companies[$awb['Contract']['company_id']].'^'.$awb['Address']['address'].'^'.$types[$awb['ContractDetail']['content_type_id']].'^'.$awb['Awb']['colie'].'^'.$kilo.'^'.$manifestDetails[$awb['Awb']['id']];
if(!isset($_COOKIE['manifest_courier']))
{
setcookie("manifest_courier", $isiCookies, $date_of_expiry, "/");
}
else
{
setcookie("manifest_courier", rawurldecode($_COOKIE['manifest_courier']).'*'.$isiCookies, $date_of_expiry, "/" );
}
And this is the javascript function that I have used to deleted the cookies :
$(window).unload(function() {
Cookies.erase('manifest_courier');
});
Please tell me why the cookies are not created if the page reload. Thanks for your help.
You don't need to do everything in views.
First off, make sure the Cookie component is included in the controller.
var $components = array('Cookie');
Then, in your function,
$isiCookies = $awb['Awb']['id'].'^'.$awb['Awb']['awb_number'].'^'.$companies[$awb['Contract']['company_id']].'^'.$awb['Address']['address'].'^'.$types[$awb['ContractDetail']['content_type_id']].'^'.$awb['Awb']['colie'].'^'.$kilo.'^'.$manifestDetails[$awb['Awb']['id']];
if($this->Session->check('manifest_courier'))
{
$this->Cookie->write('manifest_courier',$isiCookies,false,$date_of_expiry);
}else{
$this->Cookie->write('manifest_courier',rawurldecode($_COOKIE['manifest_courier']).'*'.$isiCookies,false,$date_of_expiry);
}
In view, use that Js to delete the cookie if it still exists after refresh.
Related
I am new to php. I am facing problem with sessions. I mean, after I get logged in and I click on any link in the website , its immediately getting logged out. Not sure why.
In chrome console: I entered as : document.cookie , it showing me "", then I got to understand that cookie is somehow getting deleted immediately or some other issue.
This problem exists for below 2 websites.
We have a websites like :
www.mysite.site1.com/folder1
www.mysite.site2.com/folder2
Below is my code of MySite.com/folder1
function MySession() {
$params = session_get_cookie_params();
session_set_cookie_params($params['lifetime'], '/v/folder1');
session_start();
}
function clear()
{
$_SESSION=array();
session_destroy();
}
Below is my code of MySite.com/folder2
function MySession() {
$params = session_get_cookie_params();
session_set_cookie_params($params['lifetime'], '/v/folder2');
session_start();
}
function clear()
{
$_SESSION=array();
session_destroy();
}
Setting the domain for cookies in session_set_cookie_params() only affects the domain used for the session cookie .
So to make all your cookies be available across all sub-domains of your site you need to set your cookies on root domain.
when setting the path that the cookie is valid for, always remember to have that trailing '/'.
CORRECT:
session_set_cookie_params (0, '/yourpath/');
INCORRECT:
session_set_cookie_params (0, '/yourpath');
mysite.site1.com is your base url.
when you switched from www.mysite.site1.com/folder1
to
www.mysite.site2.com/folder2
you'll surely be logged out.
Well, I am able to find out answer for my query:
since in my case I have 2 folders ie., www.mysite.com/folder1 && www.mysite.com/folder2 , then we MUST keep session_name('folder1') for 'folder1' and session_name('folder2') for 'folder2' , otherwise both folders share the same session ID and so user gets logged in automatically in folder2 (assuming if he already got loggedin folder1)
function Session() {
session_name('FOLDER_SID');
session_start();
}
Regarding more info about session_name, here: http://stackoverflow.com/a/7551430/4956785
We are trying to create a unique ID for each user that visits our site. I'm relatively new to Zend and to MVC patterns, so i'm unsure as to where the cookies should be set and how.
The php is very straight forward:
if(!isset($_COOKIE['mx_uid'])){
$expire = time()+60*60*24*30;
setcookie('mx_uid', uniqid('mx_'), $expire);
}
$lxid = $_COOKIE['mx_uid'];
I tried to place this into the View and ran into the issue that the cookie is regenerated on every new page that is loaded, so if they go to 20 pages on the site then they have 20 cookies.
Additionally, I need to use the "$lxid" variable inline on each page without refreshing, because a javascript snippet will be capturing the cookie contents.
Has anyone used cookies in this way on Zend?
If you need to set cookies once during one session place them in frontController plugin. Add to your app.ini
resources.frontController.plugins.a.class = "YourNamespace_Plugin_Cookies"
And then your plugin will look like
class YourNamespace_Plugin_Cookies extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$cookie = $request->getCookie('mx_uid');
if(empty($cookie)){
setcokkie('mx_uid',$lxid,$expire, '/');
}
}
}
You'll want to set the cookie path as well (4th param):
setcookie('mx_uid', uniqid('mx_'), $expire, '/');
Be aware that you may not be able to access the cookie within the same script in which you are setting it (i.e. it won't work until the next page they visit). So better logic might be:
if (isset($_COOKIE['mx_uid'])){
$lxid = $_COOKIE['mx_uid'];
} else {
$lxid = uniqid('mx_');
$expire = time()+60*60*24*30;
setcookie('mx_uid', $lxid, $expire, '/');
}
to ensure that $lxid will always contain a value.
I set a session variable on login subdomain, and response json from another subdomain if the login was successful, the responsed json is checked by a script and the script does a location.href = "new url". On the redirected site "new url" I want to check my session variables if the user is logged in or not, but there are no session variables set. Does location.href = "" destroy my session? How to fix this problem? session.cookie_domain is set to '.mydomain.com'.
login.mydomain.com:
$.post('http://api.mydomain.com/index.php', {action: 'login', username: username, password: password}, function(response) {
var success = $.parseJSON(response);
if(success.success == 'true') {
location.replace = 'http://my.mydomain.com';
}
});
api.mydomain.com:
session_start();
$_SESSION['active'] = true;
header('Access-Control-Allow-Origin: http://login.mydomain.com');
echo '{"success": "true"}';
my.mydomain.com:
session_start();
if(!isset($_SESSION['active']) && !$_SESSION['active']) {
header("Location: http://login.mydomain.com");
echo $_SESSION['access_token'].' test';
}
else {
echo 'Success!';
}
I had the same problem and I found when I use a relative url (location.ref="index.php"), all sessions variables exists. But when I use a absolute url (location.ref="http://mydomain.com/index.php") it kills all my session variables.
You don't seem to be calling session_start() in the second code block.
From what you're saying you could have a couple of issues contributing to this problem.
PHP cookies are set by the server when the page is loaded, no page load means no cookie is set, if you're using pure JSON with no page load then you may not be able to set your session and return it to the browser.
Also remember that PHP sessions are effectively a cookie and the rules for cookies apply, so if you're setting a PHP session at api.mydomain.com and expect it to work at my.mydomain.com it probably wont work.
You can find a viable solution to handling login data and the sessions over multiple sub-domains here
Really hope this makes sense and someone can point me in right direction. On a registration page (parent page), when you enter a license code a jQuery ajax success function loads content from another page with an appended url to include a session id:
success: function(data) {
if (data=="RegisterError") {
$("#error").show();
$("#processing").hide();
} else {
$("#contain").load("download-software.php?sessionid=xXXX #req");
}
}
The page "download-software" has the following PHP referrer check to make sure the content is being requested from the registration page via the session ID and redirects you if it's not:
<?php
$code = $_GET['sessionid'];
if(strcmp( $code , 'xXXX' ) != 0) {
header("Location: http://www.someotherpage.com");
}
?>
That works fine. Now what I need to do is in the "download-software #req" content that is loaded into the parent page, have a link that when clicked replaces the "download-software #req" content which has been loaded inside the parent page with content from another page and do the same type of session id check.
I cannot get it to work. I place the following code on the "download-software #req" content for the
<a id="beta">beta notes
$("#beta").click(function() {
$("#req").load("NT7-SP1-Download.php #betaNotes");
});`
I've also tried using the .live function. How do I start a new session and make this work?
*answer**
I used the live function on the parent page and it works fine. Making it too hard i guess.
I would refrain from using GET query string parameters and use the included PHP session functions.
use:
<?php
// initialize the session
session_start();
// assignment call
$_SESSION['key'] = 'value';
?>
You can retrieve data from the session on the same server in subsequent page requests.
When you are done with the session, use: session_destroy()
I can't seem to get a facebook connect app that I am building to log the user out (sorry no url as it's still in dev). Each time the user clicks a link with the class "logout" the following JS runs which seems to work and even shows the FB modal stating the user has been logged out.
$(document).ready(function(){
$('.logout').click(function(){
//Kill facebook Session
FB.Connect.logout(function() {
window.location = $('.logout').attr("href");
});
});
});
Upon reaching the callback above, the JS sends the user to the logout page where PHP again forces the removal of a custom session and insures that the FB session was removed. Then the user is sent back to the page they were on when they clicked the "logout" link.
//Remove our site session
Auth::logout();
/* FAIL
//Send user to FB logout page and then back here
$logout_url = $this->fb->get_logout_url( site_url( $return_to ? base64_url_decode($return_to) : '' ) );
// Clear any stored state
$this->fb->clear_cookie_state();
exit(header("Location: ". $logout_url));
*/
//FAIL
//$this->fb->logout( site_url( $return_to ? base64_url_decode($return_to) : '' ) );
//FAIL
//Remove user (is this needed..?)
//$this->fb->set_user(NULL, NULL);
//Remove the FB session cookies (in case the JS didn't)
$this->fb->clear_cookie_state();
// Redirect to privious page
redirect( ( $return_to ? base64_url_decode($return_to) : '') );
However, this whole process results in the user being right back where they were and still logged in. A second click on the link seems to do the trick and remove the session though. I have monitored firebug (w/firecookie) and the PHP logout page reports deleting the FB session cookies - yet the next page loaded seems to still use them?!
If anyone knows how to completely DESTROY ALL FACEBOOKS ahem... sessions then please speak up.
:EDIT:
I have even tried to manually remove all cookies on the logout page and it still fails
if( $_COOKIE ) {
foreach( $_COOKIE as $name => $value ) {
//Get the current cookie config
$params = session_get_cookie_params();
// Delete the cookie from globals
unset($_COOKIE[$name]);
//Delete the cookie on the user_agent
setcookie($name, '', time()-43200, $params['path'], '', $params['secure']);
}
}
My guess is that because you are starting the Facebook api classes it reads the session and sets all the cookies again your Javascript call just cleared.
The php facebook lib and the FB js lib both use the same cookienames.
(so you can login through javascript and the php lib will be logged in as well).
There is a specific function for a log out and going to a URL by the way:
FB.Connect.LogoutAndRedirect(url);
Just use the <fb:login-button> tag and make sure you have autologoutlink='true'
Then, when the user is logged in, print out the <fb:login-button> tag and it will show up as a "Logout?" button
Hope that helps.
EDIT:
The docos for login-button: http://wiki.developers.facebook.com/index.php/Fb:login-button
This worked for me (where the redirect page clears the server stuff)
FB.logout(function(response) {
window.location.href="/login/signout";
});