JavaScript and cookies
PHP and cookies
Scripted HTTP
JavaScript cookies 1
• Cookies are used to create sessions or identify a user that
returns from a earlier visit (since HTTP forgets
)
•
Two cookie types exist
– A persisten cookie is stored as a text file on the disk
– A session (or transient) cookie is stored in RAM and just lives for the session (no expire date is set when creating the cookie) – this is the default
• A cookie is a string with name=value pairs
– Cookies are like persistent variables that the browser can store and read when accessing the website in question
– Name, password and date are common cookie values – Cookie is part of the DOM as a document.cookie object
•
Cookie visibility is scoped by document origin and path
– It is configurable through cookie attributes path and domain
JavaScript cookies 2
• The browser may not store more than 300 cookies in total or
20 per web server or 4kB in size
• Persistent cookies expires after a certain
max-age
(in
seconds) when the browser will delete them
• To view persistent cookies on your computer with IE
– Navigate to Tools > Internet Options
– Select the General tab and press the button for Settings in the Browsing History section
– In the Temporary Internet Files and History Settings dialog select View files to open the folder where cookies are saved
– They are stored as files in this format: cookie:[email protected]/
• Cookie
example
content
- Cookie name - Cookie value
- Domain/path for the web server setting the cookie - Flags
Cookies in Firefox
• Firefox have a good cookie viewer
– Firefox menu > Options > Privacy > in History section choose
Cookies in Chrome
JavaScript cookies 3
• Cookies were introduced to provide a way to implement a
shopping basket (or cart)
– The boolean attribute secure specify transfer - HTTP or HTTPS
• When combined with a DB backend on the server storing
the shopping list one can continue shopping next day
– A web server typically sends a cookie containing a unique
session identifier
– The web browser
will send back that session identifier with each subsequent
request and shopping basket items are
Debug/view the cookie
• Cookies are managed by the client browser used/in question
• The cookie string contains 6 parts (last 4 are optional) – Name, value, path, domain, expires and sequrity
JavaScript cokies 4
• Cookies may be used to remember information about a user
who has visited a website in order to show relevant content
in future visits
• Many websites use cookies for personalization, based on
users preferences
– Authenticated users select their preferences by entering them in a web form and submit the form to the server
– The server encodes the preferences in a cookie and sends the cookie back to the browser. This way, every time the user accesses a page, the server is also sent the cookie where the preferences are stored, and can personalize the page according to the user preferences
• There are security risks with cookies
– A stolen persistent cookie or session cookie id may be used by someone else
– Eavesdropping (listening on network traffic) for session id cookies – Tracking cookies – see web browsing habits by looking into web
<!doctype html> <html lang="en"> <head>
<meta charset="utf-8">
<title>cookie example</title> <script>
function checkCookie() {
var username = getCookie("username");
if (username != null && username != "") alert("Welcome again " + username);
else {
username = prompt("Please enter your name to create value:", "");
if (username != null && username != "") setCookie("username", username, 365); }
} </script> </head>
<body onload="checkCookie()">
<button type="button" onclick="delCookie()">Delete Cookie</button> <script src="js/cookiefactory.js"></script>
</body> </html>
Persistent cookie
The resulting cookie string is visible in the alerts!
persistent_cookie.html
/* Cookie values cannot include semicolons, commas, or whitespace. For this reason, you may want to use the core JavaScript global function encodeURIComponent() to encode the value before storing it in the cookie. If you do this, you’ll have to use the corresponding decodeURIComponent() function when you read the cookie value. */
function getCookie(c_name) { var name, value;
var all = document.cookie; // Get all cookies in one big string
var ARRcookies = all.split("; "); // Split into individual name=value pair
for (var i = 0; i < ARRcookies.length; i++) {
name = ARRcookies[i].substr(0, ARRcookies[i].indexOf("=")); value = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1); if (name == c_name)
return decodeURIComponent(value); }
}
function setCookie(c_name, value, exdays) { var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = encodeURIComponent(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString()); document.cookie = c_name + "=" + c_value;
alert(c_name + "=" + c_value); }
function delCookie(c_name) {
if (c_name != null && c_name != null && c_name != undefined) setCookie(c_name, "", 0);
else{
var cookiedelname = prompt("Please enter the cookie name to delete:", ""); if (cookiedelname != null && cookiedelname != "")
setCookie(cookiedelname, "", 0); }
}
Session cookie with form
<script src="js/cookiefactory.js"></script>
<script>
function showCookies() {
if (getCookie("visitor") || getCookie("colorchoice")) {
document.cookieform.visitorcookie.value = getCookie("visitor"); document.cookieform.colorcookie.value = getCookie("colorchoice"); } else {
document.cookieform.visitorcookie.value = "No visitor cookie available!"; document.cookieform.colorcookie.value = "No color cookie available!"; }
}
function makeCookies() {
var visitorname = document.cookieform.visitor.value; var visitorcolor = document.cookieform.color.value; setCookie("visitor", visitorname);//expires not given setCookie("colorchoice", visitorcolor);//expires not given alert("Two cookies have been created!");
}
</script> </head>
<body style="background-color: #990033" onload="showCookies()">
<form name="cookieform" action="#"> <h1>Session Cookie</h1>
<div style="background-color: #99cc99; width: 500px; height: 220px; position: absolute; top: 80px; left: 10%;">
<p><input type="text" name="visitor" size="35" value="Write your name here" /></p> <p><input type="text" name="color" size="35" value="Write your color here" /></p> <ol>
<li>Click on the button to create session cookies<br />
<input type="button" value="Create cookies" onclick="makeCookies();" />
</li>
<li>Go to another web page on internet or reload this page.</li> <li>When you come back you will see your cookies.</li>
<li><b>Note! If you close the browser the session cookie will be lost</b></li> </ol></div>
<div style="background-color: #99cc99; width: 500px; height: 80px; position: absolute; top: 340px; left: 10%;">
<p>Cookies will be shown here:</p>
<p><input type="text" name="visitorcookie" size="35" value="" />
<input type="text" name="colorcookie" size="20" value="" /></p></div> </form>
</body>
Personal hitcounter
<!doctype html> <html>
<head>
<title>personal hitcounter</title>
<script src="js/cookiefactory.js"></script> <script>
function countHits() {
var hitNumber = getCookie('hitNumber');
if (hitNumber != null && hitNumber != "" && hitNumber != undefined) hitNumber++;
else
hitNumber = 1;
setCookie('hitNumber', hitNumber, 30);//30 days expire
return hitNumber;
} </script> </head>
<body style="background-color: #ffff99;"> <h3>Personal hitcounter</h3>
<div
style="border-style: dotted; width: 280px; height: 30px; text-align: center;"> <script>
document.write('Number of visits: ' + countHits()); </script>
</div> </body> </html>
Save username
<!doctype html> <html>
<head>
<title>cookie save username</title>
<script src="js/cookiefactory.js"></script> <script>
function fixCookie(){
var username = getCookie('username'), loginname = getCookie('loginname'), alder = getCookie('alder');
if (username != null && username != null)
alert('Hello ' + username + ' with login ' + loginname + ' and age ' + alder + ' - welcome back!');
else {
username = prompt('Hello - Kindly give your name.', ""); loginname = prompt('Kindly give a login.', "");
alder = prompt('Kindly give your age.', "");
setCookie('username', username, 365); setCookie('loginname', loginname, 365); setCookie('alder', alder, 365); }
}
function delCookies(){
delCookie('username'); delCookie('loginname'); delCookie('alder'); }
</script>
<style>
a:link {
font-family: verdana; font-size: 14pt; }
a:visited {
font-family: verdana; font-size: 14pt; }
a:hover {
font-family: verdana; font-weight: bold; font-size: 14pt; text-decoration: none; color: red; }
</style> </head>
<body onload="fixCookie()">
<p><a href="#" onclick="delCookies()">Reset the cookies</a></p> <p><a href="cookie_save_username.html">Update the page!</a></p> </body>
</html>
Cookies and PHP 1
1. HTTP request (browser)
2. HTTP response (server reply). Set-Cookie is a directive to the browser to store the cookie and send it back
3. When browser request another page the server recognize the string
* PHP setcookie – send a cookie
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Cookies and PHP 2
// http://www.w3schools.com/Php/func_http_setcookie.asp <?php
$value = "my cookie value";
// send a cookie that expires in 24 hours
setcookie("TestCookie",$value, time()+3600*24); ?>
//Different ways of retrieving the value of the cookie (after the cookie has been set):
<html> <body>
<?php
// Print individual cookies echo $_COOKIE["TestCookie"]; echo "<br />";
echo $HTTP_COOKIE_VARS["TestCookie"]; echo "<br />";
// Print all cookies print_r($_COOKIE); ?>
Web 2.0
• What is Web 2.0?
– It is the next generation web services and business models
– A common feature of Web 2.0 is that users should have a high
potential for interactivity and collaboration
• A site must meet four conditions to be called Web 2.0
– The user should be able to join and contribute to the site's
contents
– The user should be able to control their information
– The design should be rich, interactive and useful
– The use of AJAX technology
• Examples of Web services that meets the criteria for
Web 2.0
– Flickr, Facebook, live.com, Wikipedia, Google+, Google Maps
– AJAX makes the interactive part easier and better - in short it
Web 1.0 vs. Web 2.0
• What is Web 1.0 then?
– Thats the web technology we have used this far - until we
begun with DHTML (Dynamic HTML) in the course
– Whenever we need to update a HTML page we make a
request and reload the whole web page
– For example when using server-side scripting as PHP and
databases, like many e-bussiness sites do
• A Web 2.0 site
– Only update the data needed when doing HTML
request/response interaction
• AJAX and a Web 2.0 approach
– Makes it possible to send and receive data without updating
the entire HTML page
– This ability will make your web application feel faster, more
What is AJAX?
• AJAX is a way to use already existing web technologies
• AJAX involves syncronization, manipulation and
transfer technologies
• To use AJAX (Asynchronous JavaScript and XML) you
must have knowledge in
– HTML, JavaScript, CSS, DOM and
HTTP requests (how the HTTP protocol works)
– The XML is optional
• DHTML is almost as AJAX
– If we add the XMLHttpRequest method/function to DHTML
•
One of the better examples of XMLHttpRequest object
usage is Google suggest or AJAX suggest
– As you type the text a JavaScript is sending your characters to
a server which returns a list of suggestions
AJAX interaction
• The JavaScript communicate directly and asynchronously (or syncronosly) with the web server via the XMLHttpRequest object • This enabling fetching small amounts of data updating the page
without reload it
Start
XMLHttpRequest object
• All modern web browsers nowadays have support for the
XMLHttpRequest object
• The object can be created either when the page is loading or
dynamically on-demand when the user performs some action
• There are 3 important properties in the XMLHttpRequest
object
– readyState, onreadystatechange and responseText
• To perform an AJAX web server request
– Get a reference to a XMLHttpRequest object
– Configure the request method (GET, POST), URL and if it is
going to be a asyncronous or a syncronous call
– Point out the callback function, i.e. where the servers response
is going to be found (onreadystatechange) - if asyncronous
– Send the the request to the server
XMLHttp... object properties
• The readyState property keeps track of the status of the
servers response
• Every time the readyState property is changed the
onredystatechange property is signalled (executed)
• If the requst is complete we have the result in
responseText
• Possible values for readyState
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
AJAX Hello World 1
<!doctype html> <html>
<head>
<title>The Hello World of AJAX</title> <script>
// Get our global browser specific XmlHttpRequest object
var xmlHttp = getXmlHttpRequestObject();
// Returns the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest(); // IE7 and others
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP"); // IE6 and less
} else {
alert("Your browser doesn't support the XmlHttpRequest object!"); }
}
// Initiate the asyncronous request
function sayHello() {
// If our XmlHttpRequest object is not in the middle of a request, start the new asyncronous call
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
// Setup the connection as a GET call to sayhello.txt, POST is possible to
// open(method, url, async), true explicity sets the request to asyncronous (default) // if we set it to false the browser will be forced to wait for the response (usually bad!)
xmlHttp.open("GET", 'sayhello.txt', true);
// Set the function that will be called when the XmlHttpRequest objects state changes
xmlHttp.onreadystatechange = handleSayHello;
// Make the actual request body. GET requests never have a body, so you should pass null or omit the argument.
AJAX Hello World 2
// This is the callback function which is called every time our XmlHttpRequest object state changes
function handleSayHello() {
// Check to see if the XmlHttpRequests state is finished
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
// Set the contents of our span element to the result of the asyncronous call
document.getElementById('span_result').innerHTML = xmlHttp.responseText; }
}
</script> </head> <body>
<!-- initiate the asyncronous request -->
<a href="javascript:sayHello();">Say Hello</a>
<br />
<!-- used to display the results of the asyncronous request -->
<span id="span_result"></span> </body>
</html>
Math.random and requests
• Web servers usually cache pages
– Web browsers as well!
– Clear the cache on most browsers with: Ctrl + F5
• We may get an old cached page even though the
information has been updated in the backend
• Solution is to attach a random parameter to the URL
which makes the request look like a new one for the
server
• Usually needed when using POST
var xmlHttp = new XMLHttpRequest();var url = "demo_get.php";
url = url + "?name=" + myparam; url = url + "&id=" + Math.random();
xmlHttp.onreadystatechange = callbackFunc; xmlHttp.open("GET", url, true);
AJAX & PHP example 1
<script>
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest(); // IE7 and others
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP"); // IE6 and less
} else {
alert("Your browser doesn't support the XmlHttpRequest object!"); }
}
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return; }
var xmlHttp = getXmlHttpRequestObject(); xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
document.getElementById("txtHint").innerHTML = xmlHttp.responseText; }
var url = "gethint.php?query=" + str + "&id=" + Math.random(); xmlHttp.open("GET", url, true);
xmlHttp.send(); }
</script> </head> <body>
<h3>Start typing a name in the input field below:</h3> <p>Suggestions: <span id="txtHint"></span></p>
<form action="#">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" /> </form>
</body>
AJAX & PHP example 2
<?php
// Fill up an array with names
$arname = array('Anna', 'Brittany', 'Cinderella', 'Diana', 'Eva', 'Fiona', 'Gunda', 'Hege', 'Inga', 'Johanna', 'Kitty', 'Linda', 'Nina', 'Ophelia', 'Petunia', 'Amanda', 'Raquel', 'Cindy', 'Doris', 'Eve', 'Evita', 'Sunniva', 'Tove', 'Unni', 'Violet', 'Liza', 'Elizabeth', 'Ellen', 'Wenche', 'Vicky');
//get the query parameter from URL
$query = $_GET["query"];
//lookup all hints from array if length of q > 0
if (strlen($query) > 0)
{
$hint="";
for($i=0; $i<count($arname); $i++)
{
if (strtolower($query)==strtolower(substr($arname[$i], 0, strlen($query))))
{
if ($hint=="")
$hint=$arname[$i];
else
$hint=$hint." , ".$arname[$i];
} }
}
// Set output to "no suggestion" if no hint were found // or to the correct values
if ($hint == "")
$response= $query." has no suggestion";
else
$response=$hint;
//output the response
echo $response;
?>
AJAX, PHP & MySQL example
• As previous example but now we get the data from a
MySQL database instead
• A modified and corrected example from:
http://www.dynamicajax.com/
• Simplesuggest folder
– ajax_search.js
– database.php
– readme.html
– searchSuggest.php
– suggest.html
– suggest.sql
• Import sql and set
DB credentials to try
• More
Using GET or POST?
• GET is used for most regular read only requests
– when the URL completely specifies the requested resource – when the request has no side effects on the server
– when the server’s response is cacheable
• The POST method is what is typically used by HTML forms.
It includes additional data (the form data) in the request body
which often is stored in a database on the server
– Repeated POSTs to the same URL may result in different responses from the server, and requests that use this method should not be cached
– The request body (msg) should match the “Content-Type” header you specified with setRequestHeader()
function postMessage(msg) {
var xmlHttp = new XMLHttpRequest(); // New request
xmlHttp.open("POST", "log.php"); // POST to a server-side script
// Send the message, in plain-text, as the request body
xmlHttp.setRequestHeader("Content-Type", // Request body will be plain text
"text/plain;charset=UTF-8");
xmlHttp.send(msg); // Send msg as the request body
// The request is done. We ignore any response or any error.
Encoding the request body
• Form-encoded requests
– Forms are POSTed to the server, and URI encoded form data is used as the body of the request
• The encoding of a simple form might look like this
– find=pizza&zipcode=21340&radius=1km
• This form data encoding format has a formal MIME type
– application/x-www-form-urlencoded
• In Ajax a JavaScript object that you want to send to the server
might look like this which you can send as JSON or XML
• AJAX POST message example - GET, POST, JSON, XML
{
find: "pizza", zipcode: 21340, radius: "1km" }
<query>
<find zipcode="21340" radius="1km"> pizza
</find> </query>