i've a php page with a form in which i have a checkbox that user can check to select to remember field in browser next login. i'm using that code:
if(rememberCheck.checked==true){
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var cod_value=escape(codice.value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie="cod=" + cod_value+";log="+login.value;
}
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);
}
}
}
function checkCookie(){
var cod=getCookie("cod");
var username = getCookie("login");
if (username!=null && username!="" && cod!=null && cod!=""){
var usn = document.getElementsByName('usn')[0];
var codice = document.getElementsByName('codice')[0];
usn.value=username;
codice.value=cod;
}
}
The problem is that when i read cookie, it read PHPSESSID=XXXXXX, and not what i write. What can i do? can you help me?
You can do it with php too.
on login if user checked "remember me", then on php
you can do like
<?php if( isset($_POST['rem_me']) &&
$_POST['rem_me']=='on' ) {
setcookie ("code", $value, time()+(3600*24*30*12)); //set your cookie } ?>
if is there any reason why you want to do it with javascript only?
<?php
if( isset($_POST['rem_me'])){
if($_POST['rem_me']=='on'){
setcookie ("remember", $value, time()+360000);
}
}
?>
why not use jquery $post to set PHP cookies on the server instead, they are easier to work with than js cookies
Related
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);
I'm using Facebook Php SDK v3.22 which I have JavaScript set me a cookie that is read in Php
For some reason when I use an if statement like so:
if($_COOKIE['anything'] == 'some_data'){
//do something
}
My canvas page redirects to a blank page with no error caught upon logout
I see in my page info that there are no cookies in the framed canvas page but I'm a little confused as I'm using server side Php to read the cookies and how this can result in Facebook redirecting to a blank page when ever I use an if cookie statement, it's sorcery!
I'm setting my cookies with JavaScript like so:
<script language="JavaScript" type="text/javascript">
<!--
if (self != top) {;
var onsite = 'true'; document.cookie = 'domainname.com' + "=" + onsite;
}else{
var onsite = 'false'; document.cookie = 'domainname.com' + "=" + onsite;
}
-->
</script>
Use the following javascript on your Page:
<script type="text/javascript">
// Set cookie function
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 the cookie
var onsite = 'false',
domain = 'domainname.com';
if (self != top) {
onsite = 'true';
}
setCookie(domain, onsite);
</script>
And your PHP script will look like this:
<?php
// Test cookie
$domain = 'domainname.com';
if (isset($_COOKIE[$domain])) {
if ($_COOKIE[$domain] == 'true') {
// domainname.com is equal to 'true'
} else {
// domainname.com is NOT equal to 'true'
}
} else {
// cookie is not set yet
}
?>
*Note if you are trying to read the cookie before it's set, it wont really work.
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;";
}
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.
I know there is no difference between JavaScript cookies and PHP cookies. yet. I'm setting a cookie with JavaScript, and checking it with PHP.
When I check the cookie with JavaScript, it returns as set. But when I check in PHP, it returns as not set. Here's my code:
Javascript
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);
}
}
}
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;
}
function moomoo()
{
var username=getCookie("username");
if (username!=null && username!="")
{
alert("Welcome again " + username);
}
else
{
username=prompt("Please enter your name:","");
if (username!=null && username!="")
{
setCookie("moomoo",username,365);
}
}
}
HTML
<div onclick="moomoo();">click me</div>
PHP
if (isset($_COOKIE["moomoo"])) {
echo ' moomoo worked'; }
else {
echo ' moomoo didnt work';}
When I recall the moo moo() script. It alerts with my name
When I load the PHP script it says "moo moo didn't work".
THE FIX!:
Thank you for the suggestions everyone. Alas, the solution was much simpler and as usual, a stupid error. Originally the function moo moo() read:
function moomoo()
{
var username=getCookie("**username**");
if (username!=null && username!="")
{
alert("Welcome again " + username);
}
else
{
username=prompt("Please enter your name:","");
if (username!=null && username!="")
{
setCookie("**username**",username,365);
}
}
}
Therefore the first time I called the function it set a cookie named "username". Then i changed it to how it is now. So since username was already set, it didn't set moomoo. So the php function couldn't find moomoo cause it was never set. Thank you all!
When I recall the moo moo() script. It alerts with my name
It looks like the moomoo variable is not getting set in JavaScript. If your name is alerted, the else block isn't being executed.
Try checking your username cookie in php, and it will display.
Try to set the Domain and Path for the 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()) + ";domain=.mydomain.com;path=/";
document.cookie=c_name + "=" + c_value;
}
Note: Change .mydomain.com according to your domain.