CACHING TO IMPROVE PERFORMANCE

Slides:



Advertisements
Similar presentations
PHP I.
Advertisements

Cookies, Sessions. Server Side Includes You can insert the content of one file into another file before the server executes it, with the require() function.
Lecture 6/2/12. Forms and PHP The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input When dealing with HTML forms.
FILE UPLOAD.
1 Caching in HTTP Representation and Management of Data on the Internet.
Multiple Tiers in Action
CSE 154 LECTURE 13: SESSIONS. Expiration / persistent cookies setcookie("name", "value", expiration); PHP $expireTime = time() + 60*60*24*7; # 1 week.
Nikolay Kostov Telerik Corporation
Christopher M. Pascucci Basic Structural Concepts of.NET Browser – Server Interaction.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
Lecture 6 – Form processing (Part 1) SFDV3011 – Advanced Web Development 1.
Databases with PHP A quick introduction. Y’all know SQL and Databases  You put data in  You get data out  You can do processing on it very easily 
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Cookies & Sessions.
Krerk Piromsopa. Web Caching Krerk Piromsopa. Department of Computer Engineering. Chulalongkorn University.
CHAPTER 12 COOKIES AND SESSIONS. INTRO HTTP is a stateless technology Each page rendered by a browser is unrelated to other pages – even if they are from.
CSC 2720 Building Web Applications Cookies, URL-Rewriting, Hidden Fields and Session Management.
Server-side Scripting Powering the webs favourite services.
JavaScript, Fourth Edition Chapter 12 Updating Web Pages with AJAX.
5 Chapter Five Web Servers. 5 Chapter Objectives Learn about the Microsoft Personal Web Server Software Learn how to improve Web site performance Learn.
NMED 3850 A Advanced Online Design January 26, 2010 V. Mahadevan.
CSE 154 LECTURE 12: COOKIES. Including files: include include("filename"); PHP include("header.html"); include("shared-code.php"); PHP inserts the entire.
PHP meets MySQL.
Creating Dynamic Web Pages Using PHP and MySQL CS 320.
School of Computing and Information Systems CS 371 Web Application Programming PHP – Forms, Cookies, Sessions and Database.
Week seven CIT 354 Internet II. 2 Objectives Database_Driven User Authentication Using Cookies Session Basics Summary Homework and Project 2.
PHP and MySQL CS How Web Site Architectures Work  User’s browser sends HTTP request.  The request may be a form where the action is to call PHP.
INTERNET APPLICATION DEVELOPMENT Practical on Sessions.
Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1.
Chapter 6: Authentications. Training Course, CS, NCTU 2 Overview  Getting Username and Password  Verifying Username and Password  Keeping The Verification.
HTML, PHP, and MySQL: Putting It All Together. Making a Form Input tags Types: “text” “radio” “checkboxes” “submit”
CSC 2720 Building Web Applications Server-side Scripting with PHP.
Intro to PHP IST2101. Review: HTML & Tags 2IST210.
Sessions in PHP – Page 1 of 13CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: Sessions in PHP Reading: Williams.
Controlling Web Site Access Using Logins CS 320. Basic Approach HTML form a php page that collects the username and password  Sends them to second PHP.
ASP. What is ASP? ASP stands for Active Server Pages ASP is a Microsoft Technology ASP is a program that runs inside IIS IIS stands for Internet Information.
הרצאה 4. עיבוד של דף אינטרנט דינמי מתוך Murach’s PHP and MySQL by Joel Murach and Ray Harris.  דף אינטרנט דינמי משתנה עפ " י הרצת קוד על השרת, יכול להשתנות.
Creating a simple database This shows you how to set up a database using PHPMyAdmin (installed with WAMP)
Web Security Lesson Summary ●Overview of Web and security vulnerabilities ●Cross Site Scripting ●Cross Site Request Forgery ●SQL Injection.
Web Design and Development. World Wide Web  World Wide Web (WWW or W3), collection of globally distributed text and multimedia documents and files 
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Database Access Control IST2101. Why Implementing User Authentication? Remove a lot of redundancies in duplicate inputs of database information – Your.
Sessions Brendan Knight A visitor accessing your web site is assigned a unique id. This id links to specific data that remains on the server. Sessions.
SESSIONS 27/2/12 Lecture 8. ? Operator Similar to the if statement but returns a value derived from one of two expressions by a colon. Syntax: (expression)
PHP and Sessions. Session – a general definition The GENERAL definition of a session in the “COMPUTER WORLD” is: The interactions (requests and responses)
CSC 405: Web Application Engineering II8.1 Web programming using PHP What have we learnt? What have we learnt? Underlying technologies of database supported.
IS2802 Introduction to Multimedia Applications for Business Lecture 8: JavaScript and Cookies Rob Gleasure
1 DIG 3134 Lecture 6: Maintaining State Michael Moshell University of Central Florida Media Software Design.
8 th Semester, Batch 2009 Department Of Computer Science SSUET.
ITM © Port,Kazman 1 ITM 352 Cookies. ITM © Port,Kazman 2 Problem… r How do you identify a particular user when they visit your site (or any.
1 PHP HTTP After this lecture, you should be able to know: How to create and process web forms with HTML and PHP. How to create and process web forms with.
PHP Form Processing * referenced from
Unit-6 Handling Sessions and Cookies. Concept of Session Session values are store in server side not in user’s machine. A session is available as long.
IN THIS LESSON WE WILL REVIEW THE STRUCTURE OF THE INTERNET AND HOW BROWSERS ASSEMBLE WEBSITES BASED ON INSTRUCTIONS THEY RECEIVE FROM SERVERS. Internet.
COOKIES AND SESSIONS.
LOGIN FORMS.
IST 210: PHP Basics IST 210: Organization of Data IST2101.
PHP: Further Skills 02 By Trevor Adams. Topics covered Persistence What is it? Why do we need it? Basic Persistence Hidden form fields Query strings Cookies.
PHP – Hypertext Preprocessor.
GENERAL SCALABILITY CONSIDERATIONS
Block 5: An application layer protocol: HTTP
Loops BIS1523 – Lecture 10.
19.10 Using Cookies A cookie is a piece of information that’s stored by a server in a text file on a client’s computer to maintain information about.
ITM 352 Cookies.
Web Caching? Web Caching:.
Intro to PHP & Variables
MVC Framework, in general.
Building Web Applications
CSE 154 Lecture 21: Sessions.
Cookies and sessions Saturday, February 23, 2019Saturday, February 23,
Presentation transcript:

CACHING TO IMPROVE PERFORMANCE

Overview of caching After you get a result, save it so you don't have to get it again Examples – Finding the maximum of many different numbers Or any other expensive mathematical computation – Generating a really nicely-formatted image Or any other expensive formatting computation

Key steps in caching 1.Define a variable for storing the result 2.If the variable does not yet have a value a)Do whatever is needed to compute the result b)Assign the result to your variable 3.Use the value of the variable

Pros and cons of caching Pros: – Caching eliminates the need to recompute Cons: – Caching requires some storage to store values (such as RAM, or some hard drive space) – Caching gives no benefit unless the value is reused

When and when not to cache Do cache when – A value is very expensive to compute or get, AND – And that value will be needed many times Do not cache when – The result is not expensive to get, OR – The result will only be needed once, OR – There isn't enough storage available to cache

Caching works at every level!!! Web page UI Your AJAX code Web server Database or files Cache in JS variable Cache in browser Cache in session Cache in DB/files

Examples of expensive JS computations Retrieving a piece of data from the server – Such as retrieving a JSON object or XML file – Network round-trips are probably the slowest computation you can do! Prompting the user for some input – E.g., if you have a site for browsing different schools' courses, ask the user once what school he or she wants to look at – From the user's standpoint, giving input is an "expensive" operation.

Detailed example of JS caching var teamCache = {}; function getPlayers() { var team = $("#team").val(); if (teamCache[team]) fillin(teamCache[team]); else $.ajax({ url:"team"+$("#team").val()+".json", dataType:"json", error:function() {alert("Cannot retrieve.");}, success:function(result) { if (result && result.players) { teamCache[team] = result.players; fillin(result.players); } else { alert("No data provided."); } }); } function fillin(playerlist) { $("#players").text(playerlist+""); } --Choose-- Team Alpha Team Beta You need a JS variable. If you might be storing multiple values, then use an associative array. Index your array with a key. Check if your value is already saved. If so, just use it. Otherwise, just do your expensive computation Remember to save your result for reuse later on!

Caching in the browser Your AJAX code doesn't need to hit the server every single time. $.ajax({}) accepts a cache option – Tells AJAX to automatically cache every GET request in the browser's cache – By default cache == true for most versions of Internet Explorer cache == false for most other versions of browsers

Example of AJAX request to cache function getPlayers() { $.ajax({ url:“team"+$("#team").val()+”.json”, dataType:"json", cache:true, error:function() {alert("Cannot retrieve.");}, success:function(result) { if (result && result.players) { fillin(result.players); } else { alert("No data provided."); } }); } function fillin(playerlist) { $("#players").text(playerlist+""); } --Choose-- Team Alpha Team Beta Wow, just one line of code.

More control over browser caching Your server exerts some control over caching Server can specify that a certain page – Should NOT be cached at all – Should INDEED be cached if possible – Should INDEED be cached if possible, but only for a certain amount of time – Should cache in even more complex ways (that you probably don't need to know, for now) All of these OVERRIDE your AJAX cache param All these apply also to the web page

When your PHP generates some HTML, the PHP can send a cache control header – So that the browser caches the page (or not) ALSO works very nicely for JS and CSS – Put your JS and CSS in another PHP file – At the top of your PHP file, send headers – Link with your main page with and

Server telling browser NOT to cache <?php header("Expires: Tue, 1 May :00:00 GMT"); // in the past header("Cache-Control: no-cache"); echo '{"players":["Chet","Emelia","Rob","Tami"]}'; ?> <?php header("Expires: Tue, 1 May :00:00 GMT"); // in the past header("Cache-Control: no-cache"); ?> test JSON (server-side) HTML (server-side)

Server telling browser INDEED to cache <?php $nsecs = 7*24*60*60; // 7 days in the future header('Expires: '. gmdate('D, d M Y H:i:s \G\M\T', time()+ $nsecs),true); header("Cache-Control: public, max-age=$nsecs",true); ?><?php echo '{"players":["Chet","Emelia","Rob","Tami"]}'; ?> <?php $nsecs = 7*24*60*60; // 7 days in the future header('Expires: '. gmdate('D, d M Y H:i:s \G\M\T', time()+ $nsecs),true); header("Cache-Control: public, max-age=$nsecs",true); ?> test JSON (server-side) HTML (server-side)

Caching in proxy servers Remember that there might also be proxy servers between the browser and the server – The http headers shown in the preceding slides will also control caching by proxies This will affect all users behind those proxies – There are also http headers you can use to control just browsers or just proxies Under some circumstances, http cache headers are ignored – E.g., if user clears the cache, or runs out of space, or if the request is an http POST

Summary so far You can store results in JS variables – Takes some code, but you have lots of control http-based caching – Can be specified with 1 line of JS in AJAX code – Can be specified with 2 lines of PHP on server – Can be used to control browser or proxy caching – Might be disregarded

Moving to the server… Examples of expensive computations Retrieving data from the database – Such as retrieving a list of records – Especially if you need to join multiple tables or do an aggregate query Formatting data as HTML – E.g., if you have a site for browsing different schools' courses, generate the HTML once and cache it

Where should results be cached? If the results are only needed by one user – If the results are only needed in the client Then cache in JS or browser (http headers) – Else Cache in the PHP session Else – Cache in the database or a file on the server

Example of caching in the session <?php session_start(); $teamdflt = (isset($_SESSION['team'])) ? $_SESSION['team'] : ""; ?> function getPlayers() { $.ajax({ url:"mydata.php?team="+$("#team").val(), dataType:"json", cache:true, error:function() {alert("Cannot retrieve.");}, success:function(result) { if (result && result.players) { fillin(result.players); } else { alert("No data provided."); } }); } function fillin(playerlist) { $("#players").text(playerlist+""); } $(document).ready(getPlayers); --Choose-- Team Alpha Team Beta $(document).ready(function() {$("#team").val( );}); <?php session_start(); $_SESSION["team"] = $_REQUEST['team']; echo '{"players":["Team'. $_SESSION["team"]. '","Chet","Emelia","Rob","Tami"]}'; /* what is wrong with the code above? hint: security */ ?> mydata.php

Example of caching in files <?php ini_set('display_errors', 'On'); $mysql_handle = mysql_connect('oniddb.cws.oregonstate.edu', 'scaffidc-db', 'tzBs5Bf8uDAAvqiK') or die("Error connecting to database server"); mysql_select_db('scaffidc-db', $mysql_handle) or die("Error selecting database: $dbname"); mysql_query("drop table player"); mysql_query("create table player(pid integer, tid integer, pname varchar(20), primary key(pid))"); mysql_query("insert into player(pid, tid, pname) values(1,1,'Jim')"); mysql_query("insert into player(pid, tid, pname) values(2,1,'Carrie')"); mysql_query("insert into player(pid, tid, pname) values(3,1,'Karen')"); mysql_query("insert into player(pid, tid, pname) values(4,1,'Chris')"); mysql_query("insert into player(pid, tid, pname) values(5,2,'Kecia')"); mysql_query("insert into player(pid, tid, pname) values(6,2,'Pablo')"); mysql_query("insert into player(pid, tid, pname) values(7,2,'Monty')"); mysql_query("insert into player(pid, tid, pname) values(8,2,'Becca')"); $team = isset($_REQUEST["team"]) ? $_REQUEST["team"] : ""; if (!preg_match('/^[0-9]+$/', $team)) echo '{"players":["none '.$team.'"]}'; else { $filename = "team".$team.".txt"; // note, this should be a.txt; do NOT use.php; we will discuss in the security lecture if (file_exists($filename)) { echo file_get_contents($filename); } else { $rs = mysql_query("select * from player where tid = ". $team); $nrows=mysql_numrows($rs); $rv = '{"players":['; for ($i = 0; $i < $nrows; $i++) { if ($i > 0) $rv.= ','; $rv.= '"'. htmlspecialchars(mysql_result($rs,$i,"pname")). '"'; } $rv.= ']}'; echo $rv; // FYI, see also file_put_contents $file = fopen($filename,"w"); fwrite($file, $rv); fclose($file); } mysql_close(); ?> Check if file exists; Read & return if so. Otherwise, perform the expensive computation. Then put the result in the cache.

Caching in the database You could also define a blob and store the JSON string in the database This is left as an exercise for you, if you like.