Reading a cookie with jquery that was set by PHP - javascript

I'm trying to set a cookie in PHP, and then have my JavaScript/jQuery read it. As I've been trying to research the issue I've seen some people talk about server side vs. client side cookies, and other people saying cookies are just cookies and there's no difference. What I do know is that PHP sees the cookies, and JavaScript doesn't.
Here's a simplified version of the PHP file that builds the page and sets the cookies.
<!DOCTYPE html>
<?php
setcookie("card", "", time()+900, '/');
?>
<html>
<body>
<?php
$card = "a string I want in my cookie";
$_COOKIE['card'] = $card;
foreach($_COOKIE as $c => $c_value)
{
echo "Cookie named " . $c . " has value " . $c_value . "<br/>";
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery.cookie#1.4.1/jquery.cookie.min.js"></script>
<script type = "text/javascript" src = "script.js"></script>
</body>
</html>
This will correctly show the name and value of the cookie on my page. So I know I'm setting something.
But when my JavaScript runs, I don't seem to have any cookies. I tried a couple different ways to get to the value of either all cookies, or just a single target part of the cookie:
var all_cookies = document.cookie;
var aCard = $.cookie('card');
all_cookies shows up with a value of "" when I debug, and aCard just stays undefined.
So do I need to set the cookies differently with PHP? Or read them differently with either JavaScript or jQuery?

PHP's setcookie() function sets an HTTP response header that instructs the browser to set the cookie. This is only possible if you haven't sent any output yet. Calling setcookie() after you have already output the <!DOCTYPE means you should be getting a "Cannot modify header information - headers already sent" warning.
To set a cookie and make it available to Javascript, you need to set it at the very beginning of your script before generating any output:
<?php
$card = "a string I want in my cookie";
setcookie("card", $card, time()+900, '/');
// note from the manual (https://php.net/setcookie):
// Once the cookies have been set, they can be accessed
// on the next page load with the $_COOKIE array.
// ^^^^^^^^^^^^^^^^^^^^^
//
// so the "card" cookie won't be in $_COOKIE until
// the next page load. If you want it in there
// immediately, you need to set it manually:
$_COOKIE['card'] = $card;
?>
<!DOCTYPE html>
<html>
<body>
<?php
foreach($_COOKIE as $c => $c_value)
{
echo "Cookie named " . $c . " has value " . $c_value . "<br/>";
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery.cookie#1.4.1/jquery.cookie.min.js"></script>
<script type = "text/javascript" src = "script.js"></script>
</body>
</html>
Now that you've used setcookie() before generating any output, the cookie is set properly and Javascript should be able to access it from document.cookie without any trouble.

Related

Javascript does not call file

I am trying to use the solution called in here:
How to keep session alive without reloading page?
Unfortunately I can't get it to work, I have very limited experience with Javascript and jQuery.
This is my index.php
<?php
session_start();
echo session_id();
$_SESSION['id'] = session_id(); //just so there is a variable within the session
?>
EDIT: added jquery library after comment/answer
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
setInterval(function(){
$.post('refresh_session.php')‌​;
}, 60000);
</script>
And this is the refresh_session.php where I write to a file, so I can test if the file is actually being called.
<?php
session_start();
if (isset($_SESSION['id'])){
$_SESSION['id'] = $_SESSION['id']; // or if you have any algo.
}
$date = new DateTime();
$fp = fopen('data.txt', 'a');
fwrite($fp, $date->format('Y-m-d H:i:s') . " " . session_id() ."\n");
fclose($fp);
?>
If I call refresh_session.php manually, I see the date showing up in data.txt.
If I open up index.php and wait for the data.txt file to change, nothing happens.
What am I missing here?
I don't know why, but after copy-paste your javascript code – I've got strange characters in Code Snipped. It can be charset problem. Code looks good, but bracket only looks like bracket. It's not bracket. What it is? I don't know, but look at that what I've got in Code Snipped after pasting your code:
Code will execute if you write it using good charset. Take that working code:
setInterval(function(){
$.post('refresh_session.php');
alert("dsa");
}, 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
By the way – alert is of course only test, you can delete this.
So, the answer is – check your charset.

Cookies not being created JS

When running my web page the cookies are not being created I have been using IE as I know that chrome does not load cookies on local web pages.
I am loading the JS as
<script language="javascript" src="script.js" type="text/javascript"></script>
the script to set the cookies which is in the script.js file is
function SetCookie(name,val) {
document.cookie = name + "=" + val + ';';
}
and in my file for the main page I have set the cookie as shown
SetCookie('July',July);
When I run the code the cookie is undefined.
The simplest way to create a cookie is to assign a string value to the document.cookie object
document.cookie = "key1=value1;key2=value2;expires=date";
So, either July has to be a variable or you'll have to pass it as a string.
var July = 'July';
SetCookie('July', July);
OR
SetCookie('July', 'July');

Cookie set with javascript, not recognised with PHP (same domain and path)

These are my cookies:
My cookies
I'm running my website from my own computer using a WAMP server. I access my main page from http://127.0.0.1/Zulaijen/, and this is the javascript funcion to set the cookies (User and Session):
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "; expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + expires;
}
When I read them using javascript, it works fine. I get my session. Then I go to another PHP page named 'uploader.php' with this code:
if(!isset($_COOKIE['TestCookie']))
setcookie("TestCookie", "Hello World!", time()+3600);
print_r($_COOKIE);
echo("Session: " . $_COOKIE['Session'] . "<br/>User: " . $_COOKIE['User'] . "<br/>");
And the result is:
Array ( [TestCookie] => Hello World! )
Notice: Undefined index: Session in D:\wamp\www\Zulaijen\uploader.php
on line 30
Notice: Undefined index: User in D:\wamp\www\Zulaijen\uploader.php on line 30
Which means my PHP code is not reading the cookies I set with javascript. It only reads the one I set with my PHP code (TestCookie). And I don't understand why. They are within the same domain and the same path.
You should try setting cookie path. Could be that the cookie paths for PHP and JavaScript isn't matching, hence the cookie will not be shared between the two.
JavaScript cookie path:
How do I set path while saving a cookie value in JavaScript?
PHP coookie path (see path section):
http://php.net/manual/en/function.setcookie.php
I finally found out what was causing the problem (by accident). It's very confusing, but it has a very simple solution.
In order to read the cookies from PHP, you must read them from the very beginning of the file.
Doing this:
<?php print_r($_COOKIE); ?>
At the very beginning of the file (before any HTML code) prints every cookie I set correctly as it should. Even if you set them from PHP, if you don't do it from the very beginning of the file you won't be able to get them.
The reason why I was able to read the one I was setting with PHP was simply because I was setting it right before reading it, or so it seems.

How to know if php file is being called within a src="..."?

In my website I have
<script src="js.php"></script>
Question is very simple but I have no idea of the answer:
Within js.php, how can I check if the file has been called though a script src="..."?
Purpose is to change the returned HTML code of js.php depending on how this php script file is called (direct access or script src="...").
The way to do it would be to assign a session variable to true right before you call the js.php file
session_start();
$_SESSION['src'] = true;
<script src="js.php"></script>
Then in the php file
session_start();
if(isset($_SESSION['src']) && $_SESSION['src'] == true) {
// file was called from a src
$_SESSION['src'] = false; // this is important so that it can't be called from direct access
}
Cool question. Let me help ya.
I'll provide here some not 100%-reliable methods, that will work in standard, non-user-malicious cases.
First
For this solution you will be required to download mimeparser from here. It's your choice what kind of mimeparser you want to use, I found this just ad-hoc for purpose of this answer.
Theory
In theory browser is sending headers, that your script during response should match for proper browser-side parsing. Especially I have here in mind HTTP_ACCEPT header.
Code example
Once you have downloaded mimeparser, lets start with creating file test.php:
<?php // test.php
//https://code.google.com/p/mimeparse/
include_once('mimeparse.php');
$mimeMatch = Mimeparse::best_match(array('text/javascript', 'text/css', 'text/html', 'application/xhtml+xml', 'application/xml', 'image/*'), $_SERVER['HTTP_ACCEPT']);
switch($mimeMatch) {
case 'text/javascript': // via <script src>
echo('alert("this is loaded as script");');
break;
case 'image/*': // via <image src>
header('Location: http://i.stack.imgur.com/sOq8x.jpg?s=128&g=1');
break;
case 'text/css': // via <link href>
echo('body::before{content: "this is written via CSS"}');
break;
default:
var_dump('detected standard file request by matching to ' . $mimeMatch);
// if __FILE__ is first on a list, its not included
if(__FILE__ !== array_shift(get_included_files())) {
var_dump('file was included or required');
} else {
var_dump('file runs on its own');
}
// additional detect for ajax request.
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
var_dump('loaded via AJAX request');
} else {
var_dump('loaded via not-AJAX request');
}
break;
}
die();
You can visit it by now, to see that script detects, its loaded directly:
string 'detected standard file request by matching to text/html' (length=55)
string 'file runs on its own' (length=20)
string 'loaded via not-AJAX request' (length=27)
Inclusion - feature showdown
To see, whats happening with script in some special cases, you can create an example index.php:
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.php"/>
</head>
<body>
<script src="test.php"></script>
<img src="test.php"></img>
<?php require('test.php'); ?>
Description
By parsing some standard-behavior headers sent from browser, we can predict loosely, what was context of page load. It's not 100% reliable and not a very good practice, but great for writing rootkits ;) anyway.
Hopefully rest is commented-out in PHP code.
Tested with Apache serving and Chrome reading.

HTML Javascript webpage content reading into a var

Lets say I have this weblink: http://checkip.amazonaws.com/ . I've made a java program (actual program. not webpage) that reads the content of this webpage (eg. "25.25.25.25") and displays it in a jLabel (Using Netbeans IDE 1.7.3) and it works.
Now how can I read the contents of this same webpage (eg. "25.25.25.25") and display it as normal text on a webpage (The final webpage must be .html not .php or what ever)?
I dont mind any script whether is html or javascript or anything, I just please need it to work so that when the webpage is opened it can read something like:
"Your IP: 25.25.25.25"
Preferably reading the contents of http://checkip.amazonaws.com/ into
<script>var ip = needCodeHere</script>
If I can get the IP into a var or read the contents of that webpage into a var I'm happy but other code is happy to as long as it works.
Please help :( been staring at google for days and cant find a solution)
You'll need 3 files (in the same directory) to do that. A HTML file to show the ip, a PHP file to get that ip via curl, and a JS file to connect the html and the php. It would be simpler if the "final webpage" could be the ip.php itself, but let's do it this way:
1) ip.html (the "final webpage")
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="ip.js"></script>
<div id="ip"></div>
2) ip.php
<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://checkip.amazonaws.com');
$result = curl_exec($curl);
curl_close($curl);
?>
3) ip.js
$.ajax({
url: 'ip.php',
type: "GET",
success: function (data) {
$('#ip').html("Your IP: " + data);
}
});
Let me know if you need more explanation.

Categories

Resources