php cannot recognize javascript cookie - php

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.

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);

Facebook blank canvas page from php if $_COOKIE statement

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.

How to save cookie in browser using javascript

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

How do i pass a js variable from one html file to another?

My problem is pretty simple, but as i still lack proficiency in merging js,php and html, i couldn't find a solution for this problem.
The problem involves 3 files:
JS1.js
function foobar(foo){
...
}
here foo is the same foo generated from HTML1.html file
HTML1.html
...<?php
$something = Object->method();
$array = Object->anotherMethod($something);
echo "<script type=\"text/javascript\">
var foo =" . json_encode($array) . ";
</script> ";
?>
...
here i generate the json_encode(d) version of my php array
HTML2.html
...<head>
<script type="text/JavaScript" src="js/JS1.js">
</head>
<body>
...
... onClick = \"foobar(foo)\">";
...
</body>
here, basically, i need it as the parameter to run my foobar js function in JS1.js file
So my question is, how do i pass foo from HTML1.html to HTML2.html?
PS: obivously i have 2 splitted html files because i need them both and both do different things otherwise the problem would have never even occurred :) just to clear things up
In this case use a cookie :
IN HTML1 , after setting var foo, set it in a cookie
then get it from the HTML2
HELPER CODE (http://www.w3schools.com)
in js :
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;
}
and
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);
}
}
}
theres 2 ways you could do it,
1: [easyest,cleanest] set a cookie on the browser that javascript can
read. w3schools.com on javascript cookies
or
2: [this is a very bad idea] have javascript add a value to the end of all
links to pass the value

javascript empty text ajax

I have a php script and i'm using ajax with it. I have a textarea form connect with the ajax class
The problem when I pass a text like (&some text) the function return an empty text, I guess that I have a problem with (&).
The javascript function:
function sendFormData(idForm, dataSource, divID, ifLoading)
{
var postData='';
var strReplaceTemp;
if(XMLHttpRequestObject)
{
XMLHttpRequestObject.open("POST", dataSource);
XMLHttpRequestObject.setRequestHeader("Method", "POST " + dataSource + " HTTP/1.1");
XMLHttpRequestObject.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200)
{
try
{
var objDiv = document.getElementById(divID);
objDiv.innerHTML = XMLHttpRequestObject.responseText;
}
catch(e){document.write("sendFormData: getElementById(divID) Error");}
}
else
{
if(ifLoading)
{
try
{
var objDiv = document.getElementById(divID);
objDiv.innerHTML = "<img src=loading.gif>";
}
catch(e){document.write("sendFormData->ifLoading: getElementById(divID) Error");}
}
}
}
for(i=0; i<document.getElementById(idForm).elements.length - 1; i++)
{
strReplaceTemp = document.getElementById(idForm).elements[i].name;
postData += "&aryFormData["+strReplaceTemp+"][]="+document.getElementById(idForm).elements[i].value;
}
postData += "&parm="+new Date().getTime();
try
{
XMLHttpRequestObject.send(postData);
}
catch(e){document.write("sendFormData: XMLHttpRequestObject.send Error");}
}
}
Make sure your & is encoded with & if you're passing it using Javascript. All & need to be encoded, or some browsers can freak out a bit, and any validater will complain at you.
when i see HTML and & and problem, i look to make sure that my character encoding is all properly specified.
also, the code in your PHP script may be choking on an un/escaped '&' character.
In your function, if you wrap document.getElementById(idForm).elements[i].value and even strReplaceTemp (in your postData +=) line with "encodeURI()", you won't have any issues with the data being properly received.

Categories