Redirect Function Based on Cookie - php

I am using this code in my js file for redirect
setTimeout('top.location=\'http://google.com/?123\';', 1000);
Problem is my js file execute many time but i want to add some cookie code in js file so that my visitor dont redirect again and again. so what will be cookie code which execute this js file only once unless i change cookie manually

Create your code with this function in mind, using these steps in order. You can check your js reference for how to do each of these steps. I hope this points you in the right direction.
Check for an existing cookie.
If you find the cookie, do not redirect, otherwise, redirect. (This is where your existing line would come in.)
Set a cookie with a timeout value based on how often you want them to redirect.

Not tested
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
if(readCookie('redirected')!=true)
{
createCookie('redirected',true,0); // cookie will be trashed after the browser closed.
setTimeout('top.location=\'http://google.com/?123\';', 1000);
}
Read here.

Related

Cookie is not set on the first visit

Though I have set the cookie using setcookie, why does it skip to the else part during the first time of execution/ first visit?
<?php
setcookie("dan", "Sony", time()+60);
if(isset($_COOKIE['dan']))
{
echo "Set";
}
else
{
echo "Not yet!";
}
?>
P.S: I know it is a naive question and gets downvoted but I don't find a better forum than StackOverflow.
setcookie() merely arranges for the HTML headers emitted by the PHP script to contain the necessary "Set-Cookie:" header. The browser responds by storing the cookie and then regurgitating it on the next request to the site.
setcookie() does not set any variables inside the currently-executing script, which is why you're not seeing anything the first time through.
You can't get value from $_COOKIE in the same request you do setcookie, you could get it begin from the next request.
The first time you only tell the browser to set the cookie, at the time, there is no cookie data in the request header (which could get from $_COOKIE).
Set your cookies with javascript.
function createCookie(name,days,value) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
} else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) { //cookie reader function
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) { //cookie eraser function
createCookie(name,"",-1);
}
createCookie("test", 1, 1);
var mycookie= readCookie("test");
alert(mycookie);

Creating cookie for each tab seperatly

I have made a grid like google to show images and it get loaded on scroll down.
On history back click I want to show the loaded images again.
That is why, On each scroll down I have stored the last loaded page no. in cookie. But an issue come out when I load the same grid page in two tabs in same browser.
Is there any way to create cookies for each tab separately.
I have used following code to create and erase cookies.
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
//var text = document.getElementsByTagName("title")[0].innerHTML;
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
Since cookies are 'domain' wide, they aren't tab or window specific.
Also, it sounds like what your looking for is 'pushState' - which is part of HTML5.
Some useful resources:
-http://diveintohtml5.info/history.html
-https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
Also a polyfil available here:
-https://github.com/browserstate/history.js/
hope this helps!

How to delete cookie on codeigniter

I don't know how to delete a cookie. I want is when I submit a form. The cookie is also delete. I try the delete_cookie("name") but is not working. I think because the cookie I created by javascript. Please check my code to fix this problem.
This is my sample text field:
<input name="cargo_no" type="text" class="validate[required]" id="cargonumber" onchange="setCookie('cargonumberC', this.value, 365);"/>
and this is the javascript
function setCookie(cookieName, cookieValue, nDays) {
var today = new Date();
var expire = new Date();
if (!nDays)
nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
document.addEventListener('DOMContentLoaded', function() {
var themeSelect = document.getElementById('cargonumber');
var selectedTheme = readCookie('cargonumberC');
if (selectedTheme) {
themeSelect.value = selectedTheme;
}
});
Using Codeigniter, put it inside the save method of your controller:
Try:
delete_cookie('name', $domain, $path);
Details on official documentation
You can delete cookie from CodeIgniter. Use cookie helper like
$this->load->helper('cookie');
delete_cookie("name");
To delete a cookie use:
helper('cookie');
delete_cookie('remember_me');
You can't delete a cookie. The browser (or the user) has the delete the cookie(s). But, you can make the browser auto-remove the cookie by setting the expiration of the cookie to a date in the past. Here's a JavaScript example.
function deleteCookie(cookieName, cookieValue) {
document.cookie = cookieName+"="+escape(cookieValue) + ";expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}

can we retrieve and set PHP cookies using javascriopt

I've set a cookie using PHP,
setcookie("redirect", $this->currentPage(), time() + 31536000);
but I want to retrieve the value of this cookie using javascript when a certain link is clicked. How can I do that?
Yes its possible.
Try this to read cookie:
function getCookie(c_name) {
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++) {
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name){
return unescape(y);
}
}
}
// get cookie foo
var foo = getCookie('foo');
Try this to set a cookie:
/**
* Sets a cookie
*/
function setCookie(c_name,value,exdays) {
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
// set a cookie 'foo=bar' for 3 days
setCookie('foo', 'bar', 3);
Cookies are not PHP specific they are browser specific and they can be placed both from PHP and Javascript. For an easy solution, you can look into jQuery's Cookie plugin
Here's another take that attempts to be easier to understand.
Also, since cookies are encoded (both keys and values), you will want to decode them both.
var getCookie = function(name) {
var thisCookie,
keyValuePair,
key,
value,
cookies = document.cookie.split('; ') ;
for ( var i=0 ; i<cookies.length ; i++ ) {
thisCookie = cookies[i] ;
keyValuePair = thisCookie.split('=') ;
key = decodeURIComponent(keyValuePair[0]) ;
if ( key === name ) {
value = keyValuePair[1] ;
return (value != null) ? decodeURIComponent(value) : null;
}
}
}
Regarding the part about getting the cookie on a link click, you would call this function in an event handler.
Let's assume that you know how to get the link in question in JavaScript. Here's one way to get the first link in the document:
var link = document.querySelector('A') ;
In any case, once you have your link, here is how to get the value when the link is clicked:
var getCookieOnLinkClick = function() {
var cookieValue = getCookie('cookieName') ;
console.log('Cookie value is ', cookieValue) ;
}
link.addEventListener('click', getCookieOnLinkClick) ;
(Of course, most links will load a new page, so you won't have much time to do anything with the cookie value once you get it.)
Wrong concept. Cookies are stored in browsers. PHP gets/sets browser cookies through HTTP requests and responses. So both PHP and browser JS can manipulate the same cookies.

Pop-Up Window on page load

I need to have a pop-up window displayed when a page loads. What's happening is this. After an order is placed the user is redirected to their index page (main log-in page for the account) when they are redirected to the index page, I need a pop-up window to display on the page load that says something like "Your order for $variable has been saved". The $variable is defined on the previous page (where they are coming from) and I need that to carry over so I can display it in the pop-up box. Then once they click on "Ok" in the pop-up box, they are at the main page like always.
I have used a java popup box before on this project, but I am unsure of how to do one with these requirements. If there are any other/better ways to do this I am open to ideas. The layout of how this needs to work is below:
Client is logged into their account -> Order.php Page (Place an order) -> redirected to their member-index.php page (Pop-up needs to load on page load, and only when it comes from the order.php page)
Thanks!
Well from what I understand this would be the best match for you.
On previous page save a cookie (source http://www.quirksmode.org/js/cookies.html).
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
createookie("prevData", prevData, 30);
Then on the page you want the popup to appear (I suggest using an alert) (Note: you need the cookie code available on this page as well):
var prevData = readCookie("prevData");
if(prevData != null){
alert("Your order for " + prevData + " has been saved");
eraseCookie("prevData");
}
this could be in <body onLoad="code"> or simply a script in the header or anywhere really.
You can't force a popup page to open upon page load; browsers won't do that anymore. You can create a "fake" popup window by just positioning an element in the middle of the screen and decorating it so that it looks kind-of like a window. Various JavaScript libraries provide such "dialog" facilities.
`
function showpopup() {
var findString = /order.php/gi;
var referringURL = document.referrer;
var data = getQuerystring('variable');
if(referringURL.match(findString)) {
var windowprops = "left=50,top=50,width=500,height=500";
var preview = window.open("http://google.com", "preview", windowprops);
preview.document.write(data);
} else {
alert("Not order.php "+data);
}
}
function getQuerystring(key, default_) {
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
</script>
</head>
<body onload="showpopup()">
`
I assume you mean javascript. You may want to do this
<body onLoad="popup()">
Any code in the "onLoad" event should fire once the html is loaded.
If you are using Jquery, it should look like this
$("document").ready(function() {
popup();
});
You can pass your variable into the popup function.

Categories