JQuery Cookie plugin - check for presence of cookie - jquery-plugins

I hope this is a simple question, but can't find it covered elsewhere.
I simply want check for the presence of a cookie - if it's there, do nothing, but if it's not there, replace the content of a particular div (I think I know how to do this last bit.
Any ideas?

you can check cookie existence at server side before rendering page. you will get all cookie details in request object If your cookie not there,then replace the content of a particular div in server side
otherwise you can check in client side as below, if (jQuery.cookie('cookietitle')) {
// Reactions
}

You may read it like var cookieValue = $.cookie("test"); And check the cookieValue if is empty.
Check this answer for more details how to work with cookies:
How do I set/unset cookie with jQuery?

Related

Link change SESSION var

I have a listing page for an e-commerce website with various items (item_list.php). This page is generated with a PHP loop and displays each item inside a <li> element. Every item is a link to the same page, called item_details.php .
When clicking on the link i want to run a script that changes a SESSION var to a certain $id (which will be excracted from the <li> itself with .innerHTML function) and then allowing the browser to move into the next page (item_details).
This is needed so i can display the proper information about each item.
I think this is possible with Ajax but I would prefer a solution that uses JS and PHP only.
(P.S.This is for a University project and im still a PHP newbie, i tried searching for an answer for a good while but couldn't find a solution)
No JS or other client-side code can set session values, so you need either an ajax call to php, or some workaround. This is not a complete answer, but something to get you thinking and hopefully going on the project again.
The obvious answer is just include it in the link and then get it in PHP from the $_GET -array, and filter it properly.
item title
If, however, there is some reason this is not a question with an obvious answer:
1.) Closest what you're after can be achieved with a callback and an ajax call. The idea is to have the actual link with a click function, returning false so the link doesn't fire at once, which also calls an ajax post request which finally will use document.location to redirect your browser.
I strongly advice against this, as this will prevent ctrl-clicks causing a flawed user experience.
Check out some code an examples here, which you could modify. You will also need an ajax.php file which will actually set the session value. https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#product-click
2.) Now, a perhaps slightly better approach, if you truly need to do this client-side could be to use an click handler which instead of performing an ajax call or setting session directly, would be to use jQuery to set a cookie and then access this data on the item_list.php -page.
See more information and instructions here: https://www.electrictoolbox.com/jquery-cookies/
<script>
$('product_li a).click(function(){
$.cookie("li_click_data", $(this).parent().innerhtml());
return true;
});
</script>
......
<li class="product_li">your product title</li>
And in your target php file you check for the cookie. Remember, that this cookie can be set to anything, so never ever trust user data. Test and filter it in order to make sure your code is not compromised. I don't know what you want to do with this data.
$_COOKIE['li_click_data'];
3.) Finally, as the best approach, you should look at your current code, and see if there is something you can re-engineer. Here's a quick example.
You could do the following in php to save an array of the values in the session on each page load, and then get that value provided you have some kind of id or other usable identifier for your items:
// for list_items.php
foreach($item as $i) {
// Do what you normally do, but also set an array in the session.
// Presuming you have an id or some other means (here as item_id), to identify
// an item, then you can also access this array on the item_details -page.
$_SESSION['mystic_item_data_array'][$i['item_id]] = $i['thedata'];
}
// For item_details.php
$item_id = // whatever means you use to identify items, get that id.
$data_you_need = $_SESSION['mystic_item_data_array'][$item_id];
Finally.
All above ways are usable for small data like previous page, filters, keys and similar.
Basically, 1 and 2 (client-side) should only be used, if the data is actually generated client-side. If you have it in PHP already, then process it in php as well.
If your intention is to store actual html, then just regenerate that again on the other page and use one of the above ways to store the small data in case you need that.
I hope this gets you going and at least thinking of how to solve your project. Good luck!

Setting cookies not working in CodeIgniter

I wnat to set cookie with a name csrf_cookie_name with a value from this function $this->security->get_csrf_hash(); but, it is not working.
I have this in my controller:
$csrf_cookie_value = $this->security->get_csrf_hash();
$this->input->set_cookie('csrf_cookie_name', $csrf_cookie_value);
echo $this->input->cookie('csrf_cookie_name');
die();
But it is not working and nothing is echoed out.
If I try only this:
$csrf_cookie_value = $this->security->get_csrf_hash();
echo $csrf_cookie_value;
I works and a generated string is echoed out.
So, I assume that something within these next 2 lines is wrong:
$this->input->set_cookie('csrf_cookie_name', $csrf_cookie_value);
echo $this->input->cookie('csrf_cookie_name');
Thanks for your advice.
You need to specify a life time for the cookie. 0 will be a session cookie and anything else will be added to time().
If you don't specify a life time, CI will interpret that you want to delete the cookie. And that's exactly what it does :)
$this->input->set_cookie('name', 'value', 0); //expires when the browser window closes
$this->input->set_cookie('name', 'value', 3600); //expires in one hour
$this->input->set_cookie('name', 'value'); //will delete the cookie (if the cookie does not exist, you will not notice anything happening)
The reason you are not getting a cookie echoed is because the $this->input->cookie() function reads directly from the global $_COOKIE array and $this->input->set_cookie() does not populate the $_COOKIE array immediately on the server. Instead, $this->input->set_cookie() queues the cookie to be sent back and stored in the browser. Only on the users' next HTTP request will you be able to re-observe this cookie.
Secondly, and perhaps more importantly, is that I think you are using the csrf cookie improperly. To protect against cross site request forgery only requires you to enable it and set it's properties in config/config.php. That is it. There is no need to read and write it in the controllers at all.
The cookie is already there. You can consult via Javascript with:
$.cookie("<?php echo $this->config->item("csrf_cookie_name"); ?>");
I hope be useful.

MVC3 application and keeping track of what page the user initially entered

and thanks for taking the time to read my question. We will have visitors to the site that might arrive at another user's profile page. We will then encourage them to login to the site, or register as new if they are not currently members. These actions move them pretty far away from that initial page/URL they stated on, but we want to be able to "jump them" back to that page after completing login/sign-up by "keeping track" where they began. (NOTE: we're using the standard Microsoft membership provider classes, if it matters.) The "jumping back" part seems straightforward, it is the "keeping track" part that is the problem.
An illustration/example:
A visitor arrives at the site after clicking: www.mysite.com/profiles/ID=108
The visitor then leaves that page to login. How can we best capture the ID=108 somehow, so that there is a good option for the (logged-in) user to return to that profile page? I understand from reading that cookies are not optimal, but some of the other options seem to throw a monkey wrench into my thinking since the user is not yet logged-in, etc.
Any concrete steps that I can take to address this in the best MVC3 way?
EDIT:
public ViewResult MyProfile(int? id)
{
HttpCookie cookie = new HttpCookie("MySiteCookie");
cookie.Value = id.ToString();
cookie.Expires = DateTime.Now.AddYears(1); //or whatever time is appropriate
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
//do some other stuff
}
At the other end, to make use of the cookie, I've put it into the menu (temporarily) in such a way:
var MyProfileId = "";
if (Request.Cookies["MySiteCookie"] != null)
{HttpCookie cookie = request.Cookies["MySiteCookie"];
MyProfileId = Server.HtmlEncode(cookie.Value);}
and then you put it into your link
You have a couple of options:
1) You can use Session in your Controller to store the value:
Session.Remove("ID");
Session.Add("ID", "108")
And retrieve in the called Controller.
ID = Session["ID"];
2) You can pass the ID=108 on the query string from the Login Controller:
return RedirectToAction("Edit", "Profile", new { ID = "108" });
I understand from reading that cookies are not optimal
IMHO cookies are the best way to approach this. When an anonymous user lands on the profiles page simply emit a cookie containing the id of the profile that he is currently viewing. Then later when he successfully logs in read this cookie value to obtain the id and construct the redirect link and redirect him to this link.
Another possibility is to use server side session but I am mentioning this just as an alternative to cookies and not at all as something that I would recommend.
You can make the redirection to the login action adding a Url to a query string param.
Let say: www.mysite.com/login?ReturnUrl='www.mysite.com/profiles/ID=108'
I think that this is the default membership provider behaviour, but you can get the ReferrerUrl to place it in the query string on your own.

How do I prevent tampering with AJAX process page?

I am using Ajax for processing with JQUERY. The Data_string is sent to my process.php page, where it is saved.
Issue: right now anyone can directly type example.com/process.php to access my process page, or type example.com/process.php/var1=foo1&var2=foo2 to emulate a form submission. How do I prevent this from happening?
Also, in the Ajax code I specified POST. What is the difference here between POST and GET?
First of all submit your AJAX form via POST and on a server side make sure that request come within same domain and is called via AJAX.
I have couple of functions in my library for this task
function valid_referer()
{
if(isset($_SERVER['HTTP_REFERER']))
return parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) == $_SERVER['SERVER_NAME'];
else
return false;
}
function is_ajax()
{
$key = 'HTTP_X_REQUESTED_WITH';
return isset($_SERVER[$key]) && strtolower($_SERVER[$key]) == 'xmlhttprequest';
}
You might read this post regarding difference between post and get
While as Jason LeBrun says it is pretty much impossible to prevent people simulating a form submission, you can at least stop the casual attempts to. Along with implementing Nazariy's suggestions (which are both easy to get round if you really want to), you could also generate some unique value on the server side (i'll call it a token), which gets inserted into the same page as your Ajax. The Ajax would would then pass this token in with your other arguments to the process.php page whereupon you can check this token is valid.
UPDATE
see this question with regards to the token
anti-CSRF token and Javascript
You can not prevent people from manually emulating the submission of form data on your website. You can make it arbitrarily more difficult, but you won't be able to prevent it completely.

mvc redirect after delay

I'm recently new in MVC technology and i'm with a difficult
I have a UI to create a user, and when i submit the content and all content is valid i pass a message into Viewdata["INFO"] and return a View called Info with Viewdata Informing than the user was sucefully created.
But in this moment i want to Regist a some script than, after a one delay specified the client redirects automatically to the base page "Users".
Any ideas to get the best way to do it?
Meta Refresh - See if this answers your question. You can specify a duration and location. Works on any browser as well!
You could just add a META REFRESH tag to the page dynamically.
I know that it is a bit late in comparison to the time this post was initially done, but just to make sure somebody finds this post beneficial.
Here is a JavaScript function that will redirect to the mentioned URL after five seconds:
setTimeout(function() {
window.location.href = "http://YourRespectiveUserBaseUrl/;"
}, 5000);

Resources