1 / 77

Advanced PHP Sessions and AJAX

Advanced PHP Sessions and AJAX. Stateless. The HTTP Web protocol was designed to be stateless to keep transactions between a browser and server brief and cut down on the overhead of keeping connections open

varick
Download Presentation

Advanced PHP Sessions and AJAX

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Advanced PHPSessions and AJAX

  2. Stateless • The HTTP Web protocol was designed to be stateless to keep transactions between a browser and server brief and cut down on the overhead of keeping connections open • Stateless means that after a transaction takes place between the browser and server, the connection is lost and neither the browser nor server has any recollection of what transpired between one session and the next. • Each request to the server is considered a brand new request. This works well for static documents, but not so well when we need to keep track of a Web site user.

  3. Saving the State • The shopping cart is used as the most obvious reason for saving state. • As the Internet grew, people started filling up their virtual carts with groceries, music, books, prescription drugs, and even cars and homes. • It became necessary for merchants to remember what their customers purchased, their preferences, registration numbers, IDs, and so on.

  4. Sessions

  5. Concept • Asession is the time that a user spends at a Web site. • PHP provides us with a mechanism to manage sessions so that we can keep track of what a visitor is doing, what he or she likes, what he or she wants, and so on, even after the user logs off. • Like cookies, the idea is to maintain state.

  6. Session Analogy • Drycleaning: • Drop garment off and be handed a claim ticket that will be used to identify the garment when you return. • The other half of the claim ticket is pinned to your garment with the same number you have on your claim ticket. • Later when you come back, you will give your claim ticket to the attendant and he or she will use it to identify your garment in the long rack of clothes. • A session works the same way.

  7. The Session • A PHP session, like a cookie, is a way for the PHP to keep track of that Web site visitor even after he or she leaves or logs off. • When a visitor makes a request from his or her browser to retrieve a Web page as follows: http://server/homepage.php • The server program, in this example, homepage.php, is a PHP program. • PHP starts a session and sends a unique session ID number, similar to the claim ticket, back to the visitor’s browser. • This unique ID number is a long random hexadecimal number that is used to key into the user’s data. It can be sent via a cookie or added to all URLs of the pages for the site.

  8. The Session • The actual user information is saved in a session file on the server, usually in a temporary directory • The session filename contains the unique ID number for the session. • The next time the visitor asks for the page, his or her browser hands the ID number back to the server, just as you hand the claim ticket to the dry cleaning attendant.

  9. The Session • The server uses the session ID number to locate the file with the name that corresponds to the same session ID number. • The session file contains the actual session data; for example: • username, • preferences, or items in the shopping cart • information about the visitor that was stored the last time he or she visited the page. • If this is the first time the user has visited the page, his or her preferences will be collected and stored into the session file, to be retrieved later on.

  10. Session ID • By default, the session ID is sent in a cookie and the cookie’s name is PHPSESSID. • In sessions, the only data in the cookie is the session ID, not any other information about the user. • The user information is saved in a session file on the server so that the size limitation of cookies is not a factor and sensitive information is not being passed back and forth across the network.

  11. Session ID • Once the user’s browser has a session ID, it passes that ID back to the server program on every subsequent request. • The session ID is disposable, so after some time it will expire and the information associated with it will also be removed. • A session might last for a few minutes or a few hours since the last request or it could last indefinitely.

  12. Sessions with Cookies • A PHP session is started either explicitly with the session_start() function, or implicitly by registering a variable for the session with the session_register() function. • Typically, session_start() is called on top of the page, and then session variables are registered in the superglobal $_SESSION array. • When PHP starts a session, it has to check first to see whether a valid session ID already exists for this user. If a valid session ID does exist, PHP will go to the session file that corresponds to the ID number, retrieve the data from the file, and assign it to the superglobal $_SESSION associative array. • The values in this array are then made available to your program. If this is the first time the user has visited the page, PHP will create a new session ID, and the $_SESSION array will be empty.

  13. Session Start() • The session_start() function creates a session or resumes one that has already started. • The session ID is passed via a cookie, via GET/POST, or in a link. • Each page that uses a session must start the session with the session_start() function. • If the session ID is being sent by a cookie, then thesession_start() function is called before any other statements that send output to the browser. • This function always returns TRUE.

  14. Registering a Session • The data that is stored in the session file is created in a PHP script in the form of variables. • The session variables can then be referenced across page requests during the life of a session. These variables might represent the items placed in a shopping cart, a user’s login and password, a user’s color preference, and so on. • Although session_start() starts a session, it does not register session variables. To create session variables, you must register the variables in the session library.

  15. The $_SESSIONAssociative Array • To register variables for the session, the preferred way is to assign values to the superglobal$_SESSION array. • Superglobalsare available everywhere in your script, even within functions. • PHP automatically registers the $_SESSION variables for you. The global $_SESSION associative array is used to handle the session variables that will be saved on the server for the life of the session.

  16. The $_SESSIONAssociative Array • The key for the $_SESSION associative array is the name of the variable, and the value is what you are assigning to it. • To access the values in the $_SESSION associative array, you must first start a session and then extract the array values as you would any other associative array. • To unset these variables, the unset() function is used; for example, unset($_SESSION['color']). • You must use session_start() before using the $_SESSION array.

  17. Example <?php session_start(); ?> <html><head><title>Sessions</title></head> <body> <h2>Tracking Visitors with Sessions</h2> <?php 2 if ( ! isset($_SESSION)){ $_SESSION[visitor_count]=0; } else{ 4 $_SESSION[visitor_count]++; } 5 echo "You are visitor number: “.$_SESSION['visitor_count’].”<br />"; 6 echo "The session id is: “.session_id(); ?> </font></body></html> Starts the Session Checks for the $_Session array; if not set, create the visitor count variable in the array and assign zero. If the $_Session exists then the visitor count variable is incremented and displayed along with the session ID

  18. Example

  19. ExampleSetting Preferences with Sessions • Consider the following example: • One page lets the user select a favorite background color; using the session mechanism, when the user goes to another page, the color is displayed in the new page.

  20. Settings PageSelf Processing PHP Part1 <?php if( isset($_REQUEST['color'] ) ) { // Start the new session session_start(); // Set the favoritecolor for this user $_SESSION['favorite_color'] = $_REQUEST['color']; } ?> checks form submission – if it has not happened, then this will not execute and the form in part2 will be displayed If form has been submitted then the session variable favourite_color will be created with the selected color

  21. Settings PageSelf Processing PHP Part2 (HTML) <html> <body> <h1> Select FavoriteColor</h1> <form action="<?php echo $_SERVER[PHP_SELF]; ?>" method="GET"> <select name="color" > <option value="" selected>Please select</option> <option value="white">White</option> <option value="blue">Blue</option> <option value="red">Red</option> <option value="yellow">Yellow</option> <option value="gray">Gray</option> </select> <input type="submit" value="Set color"> </form></body></html>

  22. Settings Appliedin a Different Page. <?php session_start(); $favorite_color = $_SESSION['favorite_color']; ?> <html> <body bgcolor="<?php echo $favorite_color; ?>"> <h1>Your FavoriteColor</h1> Your favoritecolor is <b><?php echo $favorite_color; ?></b>. </body> </html>

  23. Example Comments • Notice that in this example the only connection between the page that sets the color and the page that displays the coloris the session. • Unlike forms where one page collects the information and passes it to another page via a GET/POST request, the session pages need not be connected. In other words, we can set the color, then surf anywhere else and once we come back, the color should still be set. • Note that this “stickiness” is valid only as long as the session is valid. A typical session might expire within an hour or two, or never. • This is configured in the php.ini file and is up to the server setting to manage it. Also, if the user restarts the computer or the Web browser, his or her session ID might be lost and the next visit to these pages will create a brand-new session.

  24. Session Name • The session name refers to the session ID stored in both cookies and URLs. • Instead of using the default name of your session, PHPSESSID, you can give your session a different name. • However, remember that if you change the name of the session, every page that uses your application must call session_name() with the new name before calling session_start(). • Thesession_name() function will return the current session name if given no arguments, or reset the session name when the first argument is a string

  25. Example Before changing the name of the session, the session_name() function returns the name of the current session. <?php ob_start(); if( isset($_REQUEST['color'] ) ) { // Start the new session with a new name print "The previous session name was ".session_name().".<br />"; session_name("ColorSite"); print "The new session name is ".session_name().".<br />"; session_start(); // Set the favoritecolor for this user $_SESSION['favorite_color'] = $_REQUEST['color']; } ?> The session_name() function will change the name of the session to ColorSite. Now any page using this session will also need to call session_name('ColorSite')before starting a new session. A session is started for this page. The session’s name is "ColorSite".

  26. Example Cont’d <html> <head><title>Session Name</title></head> <body> <h1> Select FavoriteColor</h1> <form action="<?php echo $_SERVER[PHP_SELF];?>" method="GET"> <select name=color> <option value="" selected>Please select</option> <option value="white">White</option> <option value="blue">Blue</option> <option value="red">Red</option> <option value="yellow">Yellow</option> <option value="gray">Gray</option> </select> <input type="submit" value="Set color"> </form> </body> </html> This is a self-processing PHP script. It will present the form and then process it.

  27. At the bottom of the page or a new page To use the session ID from the previous session, this page needs to be able to refer to the correct session by its name. A new session is started after the session name was changed. <?php session_name('ColorSite'); session_start(); $favorite_color = $_SESSION['favorite_color']; print_r($_SESSION); ?> <html> <body bgcolor="<?php echo $favorite_color; ?>"> <h1>Your FavoriteColor</h1> Your favoritecolor is <b><?php echo $favorite_color; ?></b>. </body></html> <?php ob_end_flush(); // Flush the buffer and end output buffering ?>

  28. All in the samePage If all the code is on the same self processing page this is what it would look like.

  29. In different PagesPassing the Name Alternatively, passing the session name to a new page and starting the session the selection will be “remembered”

  30. Implementing a LOGIN systemwith SESSIONS

  31. The Example • The following example consists of three separate files. • The first file is a simple HTML form, the login page, where the user enters a username and password. • The second file, the authentication page, is a PHP script that will verify the username and password, and establish a “logged in state” if the username and password are valid. This file will also be used for logging out the user. The action to log in depends on the parameter (login) provided by the POST method from the HTML form (hidden input element). The action to log out is performed after the user has logged on, been redirected to the third page with protected content, and clicks on the logout link. • The third file is a PHP script that will show protected content only if the user is logged in. This file also describes a simple way to conditionally display a whole HTML block. • Sessions are used to remember users who are logged in and their password. In a real-world situation, you will probably use a database to store the username and password, and the protected content could be stored in a text file or database.

  32. File 1: login.html ##### login.html ##### <html><head><title>Simple login page</title></head> <body> <p> <a href="protected.php">Protected content</a></p> <p> Type phpbee for both username and password </p> <form action="auth.php" method="post"> Username<br /> <input type="text" name="username"><br> Password<br /> <input type="password" name="password"><br> <input type="hidden" name="login"><br> <input type="submit"> <input type="reset"> </form> </body> </html> This hidden field “login” is used to process the login process

  33. File 2: auth.php <?php session_start(); // User is logging in if (isset($_POST["login"])){ if ($_POST['username']=="phpbee" && $_POST['password']=="phpbee"){ $_SESSION["Authenticated"] = 1; } else { $_SESSION["Authenticated"] = 0; } session_write_close(); header("location:protected.php"); } // User is logging out if (isset($_GET["logout"])){ session_destroy(); header("Location:login.html"); } ?> Check for login Check for logout

  34. File 2: auth.php <?php session_start(); // User is logging in if (isset($_POST["login"])){ if ($_POST['username']=="phpbee" && $_POST['password']=="phpbee"){ $_SESSION["Authenticated"] = 1; } else { $_SESSION["Authenticated"] = 0; } session_write_close(); header("location:protected.php"); } // User is logging out if (isset($_GET["logout"])){ session_destroy(); header("Location:login.html"); } ?> Checks for username and password Sets the Session[“Authenticated”] variable to 1 is correct or 0 if not correct session_write_close() Stores the session data and closes the session

  35. File 3:protected.php <?php session_start(); ?> <html><head><title>Protected page</title></head> <body> <?php if (isset($_SESSION["Authenticated"]) && ($_SESSION["Authenticated"] == 1)){ ?> <h2>Protected content</h2> <p>Hello. Since you are logged in, you can view protected content</p> <p>You can also <a href="auth.php?logout">log out</a></p> <?php }else{ ?> <h2>You are not logged in</h2> <p>Hello. Since you are not logged in, you can not view protected content</p> <p>But you can <a href="login.html">log in</a></p> <?php } ?> </body></html> Checks for Authenticated session if authenticated – access protected content Link to logout as part of protected content section if Not authenticated – a message is diplayed with a link to the login page

  36. AJAX

  37. What is AJAX? • AJAX stands for Asynchronous Javascript and XML. • Although AJAX is not a technology, it mixes well-known programming techniques in an uncommon way to enable web developers to build internet application with more appealing user interfaces than those to which we have become accustomed.

  38. What is AJAX? • By working as an extra layer between the user’s browser and the server, Ajax handles server communications in the background, submitting server requests and processing the returned data. • The results may then be integrated seamlessly into the page being viewed, without that page needing to be refreshed or a new on loaded.

  39. How the Web Works • The WWW operates using a client/server networking principle through various protocols, of which the most important is HTTP • When an URL is entered into the browser, the browser is being asked to make an HTTP request of the particular computer having that web address • On receiving the request, that computer returns (“serves”) the required page to the requesting computer in a format that the browser can interpret and display.

  40. How the Web Works • The HTTP request contains several pieces of information needed to identify and serve the page correctly: • The domain at which the page is stored (i.e. somedomain.com) • The name of the page (filename) • The name and values of any parameters that are sent (optionally) with the request

  41. Web Servers • A Web server is a program that interprets HTTP requests and delivers the web page in a form that can be interpreted by the requesting browser. • The best known server application is the Apache Web Server (http://www.apache.org), an open source project used to serve millions of websites around the world. • Another example of a web server application is Microsoft IIS (Internet Information Services), often used in host computers running the MS Windows OS

  42. Server Side Programming • Server-side programs, scripts, or languages, refer to programs that run on the server computer. • Some examples of languages and tools available for server side programming: • PHP • Java • ASP (only available on servers running windows)

  43. Server Side Programming • Sophisticated server setups often also include databases of information that can be addressed by server-side scripts. • In general server side scripts are designed to pre-process a web page before it is returned to the browser. • This allows web pages to be served with rich and varied content that would be beyond the scope of any design using only static pages (pages with fixed content).

  44. Client-SideProgramming • Client-side programming happens right inside the user’s browser after the page has been received. • Such scripts allow us to carry many tasks relating to the data in the received page, including performing calculations, changing display colours and styles, checking the validity of user input, etc. • JavaScript is one of the most popular scripting languages available (and is an integral part of AJAX)

  45. HTTP • HTTP defines a set of rules regarding how messages and other data should be formatted and exchanged between servers and browsers. • Ajax sends server requests using the HTTP protocol, so it is important to recognise the different types of requests and the responses that the server may return. • Ajax applications need to construct HTTP requests to query the server and will base decisions on about what to do next on the content of HTTP responses from the server

  46. The HTTP Request • After opening a connection to the intended server, the HTTP client transmits a request in the following format: • An opening line • Optionally, a number of header lines • A blank line • Optionally, a message body

  47. The opening line is generally split into 3 parts: the name of the method, the path to the required server resource and the http version being used: • GET /scis.ulster/index.html HTTP/1.0 • HTTP request methods include: POST, GET, PUT, DELETE an HEAD.

  48. Header lines are used to send information about the request, or about the data being sent in the message body. • One parameter and value pair is sent per line, the parameter and value being separated by a colon: • User-agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0 • Accept: text/plain, text/html

  49. The HTTP Response • In answer to a request, the server typically issues an HTTP response, the first line of which is often referred to as the statusline. • In that line, the server echoes the HTTP version and gives a response status code and a short message known as a reason phrase. • HTTP/1.0 200 OK

  50. Common Status Codeand Reason Phrases • Detailed list: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

More Related