I've working on project where lots information stored in Cookies.
We've using PHP Laravel 5.2 framework and jQuery library 1.9. Every thing working fine but when trying to read a cookies with jQuery that created with Laravel PHP code its return nothing but when checked it in browser cookies and read with PHP Laravel its working fine
Laravel Code:
Cookie::queue('COOKIE_NAME', $value, $minutes); //Create a cookie
jQuery Code:
var cookieValue = $.cookie("COOKIE_NAME"); //Return nothing
After few minutes of tested, I found this Is it possible to read HTTPONLY cookies with jQuery?. It means you cannot read HttpOnly cookies, so you should compact cookies value to the view instead or made it available like so, but you will deal with security issues I guess.
Cookie::queue('COOKIE_NAME', 'MyValue', 60, null, null, false, false);
With this kind of setting, you can read your cookies with jquery cookies.
P/S: Cookies value will be encrypted with base64, so you need to decrypt it before using.
Hope this help
You can either make ajax request to retrieve the cookies from your controller or you can create a meta tag as
<meta name="cookie" content="{{ cookie_function() }}" />
in your blade.php file. Then using jquery
var cookieValue = $('meta[name="cookie"]').attr('content');
Related
I'm newbie learning laravel and have the following in my route file::
Route::get("/setcookie", function(){
$cookie = Cookie::make("low-carb","almond cookie",30);
return Redirect::to("getcookie")->withCookie($cookie);
});
Route::get("/getcookie", function(){
$cookie = Cookie::get("low-carb");
return View::make("getcookie")->withCookie($cookie);
});
I set a cookie and redirect to a different page. I want to be able to show the cookie via javascript dialog box in a view page. The "getcookie" view page looks like::
<html>
<body>
this is the cookie page
<script language="javascript">
window.onload = showCookies;
function showCookies(){
alert("Cookie is: " + document.cookie);
}
</script>
</body>
</html>
The only thing i see on the popup dialog box is "Cookie is". The value am expecting doesn't show up.
I know definitely that am doing something wrong because when i check the cookies in the chrome developer tools, i see for the "setcookie" route, the keys REQUEST COOKIE and RESPONSE_COOKIE (laravel_session and low-carb) both have values but for the "getcookie" route where it is redirected to, the REQUEST COOKIE key in chrome has both "laravel_session and low-carb" but the RESPONSE_COOKIE key only has the "laravel_session" and the "low-carb" key-value is missing.
What am i doing wrong?
By default Laravel cookies are marked as httponly - this means that they they can't be accessed via JS. This is often what you want, hence it being the default.
If you look at the source here: https://github.com/laravel/framework/blob/master/src/Illuminate/Cookie/CookieJar.php#L41, you'll see that the method signature looks like:
public function make($name, $value, $minutes = 0, $path = null, $domain = null, $secure = false, $httpOnly = true)
where the last variable passed in is the httpOnly variable.
So, if you change from:
Cookie::make("low-carb","almond cookie",30);
to
Cookie::make("low-carb","almond cookie",30, null, null, false, false);
Then your cookie will not be marked as httponly, and will be accessible via JS.
You can check if a cookie httponly or not by using your browsers dev tools, in Chrome's Dev Tools go to Resources, then to Cookies, then to oyur domain, and there is a column in that table called HTTP - it has a Tick if that cookies is HTTPonly.
Edit: All cookies are encrypted and signed in Laravel, so that users can't tamper with them. Not 100% on this personally - $_SESSION is for persistent data that the user can't edit, $_COOKIE is for data that you want the user to be able to read and edit. Anyway, just use PHP's native:
setcookie("low-carb", "almond cookie", time()+(30*60));
instead of the laravel method if you want to do this.
You might also want to think whether there is a "better" way to deal with this - perhaps you don't need Cookies for this anyway (remember they are sent with every request that matches the cookie's path, CSS, JS, images, fonts - everything)
I am developing w php web site. Here I have set a php cookie
setcookie('hotelId',$resHotel);
I want to check whether it’s set or not using jquery or javascript. I have used the following code
if($.cookie('hotelId')) {
alert("yes");
};
But it's not working
Is there is any way to find PHP cookie is exist or not in jquery
Thanks
That should work if these two conditions are met:
you have installed the extra library that you need to use $.cookie()
you have called setcookie() before outputting any part of your html
Are you sure that you have the right libraries loaded into the page? I don't think cookie behavior is included with jQuery by default.
You can view cookies manually easily. The method varies a little from browser to browser, but (in Firefox, for example) if you go to Preferences > Privacy > remove individual cookies, you can browse through them and see their contents. This can help you debug whether your php code is setting the cookie as desired.
First get the specified cookie as follows
var cookie=$.cookie("set");
if(!cookie)
{
$.cookie("set","foo"); //if there is no cookie set it
}
I am using Codeigniter with the TankAuth library installed and trying to upload to index.php/requests/doUpload from swfupload but can't access the page as authenticated. I have read many posts around the net about similar problem and tried to set $config['sess_match_useragent'] = FALSE; but still no difference. I have ended up skipping the login check in my controller for testing purposes. But now I need to access tankAuth library from my controller to get the current logged in user ID. It is requested in my application and cannot skip it, I really need to pass the logged in user id to that doUpload model. I have setup controller like this:
function doUploadFileFn() {
if (!$this->tank_auth->is_logged_in()) {
return;
} else {
$user_id = $this->tank_auth->get_user_id();
$this->load->model('requests/doUploadFile');
$this->doUploadFile->uploadData($user_id);
}
}
Now, it does not pass the is_logged_in() check, as I learned from other posts, CI deletes the session but I have setup the config not to match the user agent but still not working.
Is there any solution to this out there ?
Following the tutorial in the CI forums I was able to achieve what you are asking for.
1) Put this in the SWFUpload JS config:
post_params: {"<?php echo $this->config->item('sess_cookie_name'); ?>" :"<?php echo $this->session->get_cookie_data(); ?>"},
2) And place the MY_Session.php file in your application/libraries/ folder.
3) The new library should be loaded the moment the view is loaded if not (for some reason) then load your library in the controller.
P.S: You need to set:
$config['sess_match_useragent'] = FALSE;
Otherwise a new session will be created for a useragent Shockwave Flash
EDIT: Okay, based on your comment..you really need to set your post_params setting to your current session so it can be sent when the flash post to your controller, now in your case the best thing I could think of is the below:
Your externalUntouchableJsFile.js:
// JS scripts...
...
var swfu = new SWFUpload({
...
...
post_params: GLOBAL_VAR,
...
});
...
// rest of your JS
And in your PHP view and before loading this JS file have something like:
<script>
var GLOBAL_VAR = {};
<?php if(session_is_there) { ?>
GLOBAL_VAR = {"<?php echo $this->config->item('sess_cookie_name'); ?>" :"<?php echo $this->session->get_cookie_data(); ?>"}
<?php } ?>
</script>
<script type="text/javascript" src="<?php echo base_url() ?>path/to/js/externalUntouchableJsFile.js"></script>
EDIT 2: Since you are using an external js file, you may forget to define the global variable so use:
post_params: (typeof GLOBAL_VAR === 'undefined') ? {}:GLOBAL_VAR,
It bears mentioning that the Flash file should be served from the same domain as your CI site or one won't be able to read the other's cookies. Also make sure that the login cookie path is set to the root path. If SWFUpload can not read the login cookie, it can not send it either.
Flash has limited access to session cookies, as documented here in the SWFUpload forum. Is it possible that you've set the auto login to avoid setting an expiration (in config/tank_auth.php), thereby making it a session cookie? If that is the case, then the SWFUpload SWF may not be able to access or send the autologin cookie value, depending on the version of Flash player on the computer. Double-check your cookie expiration values using a debug tool like Firebug to see if this is the case. If the upload works when you check a "remember" me box but not otherwise, that would indicate a session cookie problem.
To force the SWF to pass the TankAuth cookie value on file uploads, you could first overload the cookie helper get_cookie function to look in either the $_COOKIE array or the $_POST array for values. Then, it appears that with SWFUpload v2 you can send additional POST values along with the upload, and this would be the way to send the autologin key, which would then allow your controller to get the user_id. But before hacking the Cookie helper, make sure your moving parts are working first, as described in the first paragraph.
I have managed to apply a rough fix for this by passing the logged user ID in the URL, and getting it from Javascript with URL functions. It's the best method I can rely to right now, it doesn't bother me too much that the user ID is visible because I'm using a managed iframe to display that specific part of the app and the app is for internal company use only.
Thanks for your answers.
First of all, I'm using KohanaPHP Framework.
I've impletemented SWFUpload successfully, working quite nice. I'm having only one issue.
The main problem is I need to allow users to upload attachments before submitting form. So I decided to use Session var to store attachments array. Unfortunately, it is working inly if I use HTML upload (based on iframe), but not when I use SWFUpload.
I tried to Google for that, but without any working solution. Any ideas?
Update & Solution
Basically, I didn't know there's an issue with Flash and sessions. Providing the same session id didn't helped me because I got unlogged. Anyway I got a solution for people with the same issue.
I created an unique ID of an item. I upload files to temporary directory, then... I'm scanning this directory and I'm adding uploaded filenames to session.
Tom
What you need to is pass the session id to SWFUpload by hand. In a nutshell, you do this in your template:
<script type="text/javascript">
var PHPSESSID = <?php echo json_encode(session_id()); ?>;
</script>
Then you do this with your SWFUpload code:
var settings = {
post_params: {"PHPSESSID" : PHPSESSID},
/* the rest of the settings */
};
And finally, in your application code, before you call session_start, you need to do this (usually just in your index.php or whatever bootstrap you use):
// Restore session that came from SWFUpload
if(isset($_REQUEST['PHPSESSID']))
session_id($_REQUEST['PHPSESSID']);
After this session_start() will use the correct session even for SWFUpload requests.
Just want to know if anyone have the same problem.
The website need to login to perform certain task. We use stock Auth component to do the job.
Everything is fine until it hits an interface which build in Flash. Talking to Amf seems fine. But when the Flash player try to talk to other controller - got redirect because the session in not presented.
So basically when a user login - I need to somehow find a way to login the Flash player in as well.
ADDITION:
This only solve half of the problem.
Backtrack a little bit. How the Auth components evaluate the requester?
If the Session.checkAgent is true. They check if its the last one. So Flash has no chance they have a different Agent string.
OK now - Auth check them out - what? The Session cookie they store earlier ... so fail again.
UPDATE
Thanks for all the answers.
I have tried the suggested solution. Only one problem.
I am using Amf (as Cakephp Plugins) when I tried to test if the $this->params['actions'] is start with amf - it works sometime doesn't work sometime. Looking at "Charles" I can see they all call to the amf controller. Very puzzling ....
in config/core.php
try
Configure::write('Session.checkAgent', false);
It appears that if you manage to call your Session->id($sessionId) before any call to Session->read(), Session->check() or Session->write(), you don't need to bother with all the destroy old session, update userAgent and delete cookie stuff.
use this in beforeFilter action of your controllere called by flash:
if ($this->action == 'flashCalledAction') {
Configure::write('Security.level', 'medium');
//Using instead the session specified
$this->Session->destroy();
$this->Session->id($_REQUEST['sessionId']);
$this->Session->start();
// We revert to the original userAgent because starting a new session modified it
$this->Session->write('Config.userAgent', $_REQUEST['userAgent']);
// We delete the flash cookie, forcing it to restart this whole process on each request
setcookie(Configure::read('Session.cookie'), '', time() - 42000, $this->Session->path);
}
then you have to pass these 2 params in each flash call to this controller:
param: 'userAgent' -> value: '$this->Session->read('Config.userAgent')'
param: 'sessionId' -> value: $this->Session->id()
http://blogs.bigfish.tv/adam/2008/04/01/cakephp-12-sessions-and-swfupload/
This is specifically for swfUpload but the process of appending the session_id to the urls and the settings for checkAgent and session security are covered and should help point you in the right direction.
Flash doesn't send the cookie along with its requests, that's why Cake doesn't log it in. The way I do it is: you need to somehow pass $this->Session->id() along with your flash requests. That is probably the hardest part because some flash application doesn't let you tag some info along in the request. Then write a component (FlashComponent, or whatever you want to call it) that check if it's a flash request, then look for the session id in its request and set the session id. You need to include this component before 'Auth': so var $components = array('Flash','Auth',...) to intercept the request before Auth does.
Or you can set Auth->allow list, but then you will expose these actions to non-authorization, and the action won't know who the current logged in user is (unless you can pass something in the flash request, in that case, use my first solution).