1 / 36

Lecture 8

Lecture 8. Sessions 27/2/12. ? Operator. Similar to the if statement but returns a value derived from one of two expressions by a colon. Syntax: (expression) ? Returned_if_expression_is_true: returned_if_expression_is_false;. Example. <html> <head> <title>Example</title> </head>

tuwa
Télécharger la présentation

Lecture 8

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. Lecture 8 Sessions 27/2/12

  2. ? Operator • Similar to the if statement but returns a value derived from one of two expressions by a colon. • Syntax: (expression) ? Returned_if_expression_is_true: returned_if_expression_is_false;

  3. Example <html> <head> <title>Example</title> </head> <body> <?php $mood="sad"; $text=($mood=="happy")?"I’m in a good mood":"Not happy but $mood"; print "$text"; ?> </body> </html>

  4. Date • The PHP date() function is used to format a time or a date • The PHP date() function formats a timestamp to a more readable date and time.

  5. Example <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=windows-1252" http-equiv="Content-Type" /> <title>Untitled 1</title> </head> <body> <?php echo("Result with date():<br>"); //The ISO-8601 numeric representation of a day (1 for Monday through 7 for Sunday) echo(date("l") . "<br>"); //d - date in numbers //S - suffix for date //F - A full textual representation of a month (January through December) //Y - A four digit representation of a year //h - 12-hour format of an hour (01 to 12) //i - Minutes with leading zeros (00 to 59) //s - Seconds, with leading zeros (00 to 59) //A - Uppercase AM or PM echo(date("l dS \of F Y h:i:s A") . "<br>"); ?> </body> </html>

  6. Server Side Includes • You can insert the content of a file into a PHP file before the server executes it, with the include() or require() function • The two functions are identical in every way, except how they handle errors • The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error)

  7. Include Files • These two functions are used to create functions, headers, footers, or elements that can be reused on multiple pages • This can save the developer a considerable amount of time • This means that you can create a standard header or menu file that you want all your web pages to include

  8. include() The include() function takes all the text in a specified file and copies it into the file that uses the include function.

  9. <?php include("inc2.php"); ?> <html> <body> <h1>Welcome to my home page</h1><p>Some text</p> </body> </html>

  10. Include File – incnew.php <html> <body> <a href="http://www.yahoo.com">Yahoo</a> | <a href="http://www.hotmail.com">Hotmail</a> | <a href="http://www.ireland.com">ireland</a> </body> </html>

  11. The require() Function • Identical to include(), they only handle errors differently • The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error)

  12. Sessions • When you are working with an application, you open it, do some changes and then you close it • The computer knows who you are. It knows when you start the application and when you end • But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state

  13. Sessions • A PHP session allows you to store user information on the server for later use (i.e. username, shopping items, etc) • Session information is temporary and will be deleted after the user has left the website • If you need a permanent storage you may want to store the data in a database • A PHP session variable is used to store information about, or change settings for a user session • Session variables hold information about one single user, and are available to all pages in one application

  14. Session Variables • Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID • The UID is either stored in a cookie or is propagated in the URL

  15. Starting a session <?php session_start();?> <html> <body> </body> </html> This code register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session.

  16. Storing a session variable <?php session_start(); // store session data $_SESSION['newuser']=1; ?> <html> <body> <?php //retrieve session data echo "New user has viewed the page=". $_SESSION['newuser']; ?> </body> </html>

  17. Session Example <?php session_start(); if(isset($_SESSION['pageview'])) $_SESSION['pageview']=$_SESSION['pageview']+1; else $_SESSION['pageview']=1; echo "Number of times page viewed by user=". $_SESSION['pageview']; ?>

  18. Killing a Session • If you wish to delete some session data use the unset() or the session_destroy() function • The unset() function is used to free the specified session variable • session_destroy() will reset your session and you will lose all your stored session data

  19. End a Session <?php session_start(); if(isset($_SESSION['pageview'])) $_SESSION['pageview']=$_SESSION['pageview']+1; else $_SESSION['pageview']=1; echo "Number of times page viewed by user=". $_SESSION['pageview']; unset($_SESSION['pageview']); ?> <?php session_destroy(); ?>

  20. More Sessions • A PHP session is started either explicitly by session_start(), or implicitly by registering a variable for the session, using session_register() • Call session_start() on top of the page, so that session variables are available to your script, and register variables to the session later in the script

  21. More Sessions • if you registered your session variables with session_register() in the head of the script and left out the session_start() call • session_register() calls session_start() internally, if the session isn't started yet • When you start a session, the following happens: • PHP checks whether a valid session ID exists • If there is no session ID, PHP creates a new ID • If a valid ID exists, the frozen variables of that session are reactivated and introduced back to the global namespace

  22. Sessions • Note that this function takes the name of a variable as argument, not the variable itself • You can use session_unregister() to remove variables from the session, for example, when the user removes a product item from the shopping cart

  23. <?php session_start(); print("<html><pre>"); $_SESSION["MyLogin"] = "Ciara"; print("A value saved in the session named as Login.\n"); $_SESSION["MyColor"] = "Blue"; print("A value saved in the session named as Colour.\n"); print("Click <a href=newsess2.php>Next Page</a>"." to retrieve the values.\n"); print("</pre></html>\n"); ?> <html> <head> <title>New Page 1</title> </head> <body> </body> </html>

  24. <?php session_start(); print("<html><pre>"); $myLogin = $_SESSION["MyLogin"]; print("Value of MyLogin has been retrieved: ".$myLogin."\n"); $myColor = $_SESSION["MyColor"]; print("Value of MyColor has been retrieved: ".$myColor."\n"); print("</pre></html>\n"); ?> <html> <head> <title>New Page 1</title> </head> <body> </body> </html>

  25. PHP Cookies • Cookie is often used to identify a user • A cookie is a small file that the server embeds on the user's computer • Each time the same computer requests a page with a browser, it will send the cookie too • With PHP, you can both create and retrieve cookie values

  26. How to create a cookie? • The setcookie() function is used to set a cookie • The setcookie() function must appear BEFORE the <html> tag • Syntax • setcookie(name, value, expire, path, domain);

  27. setcookie(name, value, expire, path, domain); Name = $_COOKIE[“cookiename”] Value = value of cookie Expire= expiry time of cookie Path=the path on the server on which the cookie will be available e.g. test/exam/ Domain = the domain on which it will be available e.g. example.com Secure= whether or not it should use a secure HTTP connection

  28. How to retrieve a Cookie value? The PHP $_COOKIE variable is used to retrieve a cookie value Use the isset() function to find out if a cookie has been

  29. Cookie Example <?php setcookie("user","NoraBatty",time()+3600); setcookie("age", 6 ,time()+3600); setcookie("country","Ireland",time()+3600); ?> <html> <head> <title>Set Cookie and Read Cookie on same page</title> </head> <body> <br> <?php echo $_COOKIE["user"]; echo "<br>"; echo $_COOKIE["age"]; echo "<br>"; echo $_COOKIE["country"]; ?> </body> </html>

  30. How to delete a cookie? • When deleting a cookie you should assure that the expiration date is in the past • Example <?php // set the expiration date to one hour agosetcookie("user", "", time()-3600); ?>

  31. If your browser does not support cookies? • If your application deals with browsers that do not support cookies, you will have to use other methods to pass information from one page to another in your application • One method is to pass the data through forms

  32. Cookie Example <?php setcookie("veg","carrot", time()+3600); ?> <html> <head> <title>New Cookie</title> </head> <body> <?php if (isset($_COOKIE["veg"])) print $_COOKIE["veg"]; else print "<p>Hello. This may be your first visit</p>"; ?> </body> </html>

  33. Cookies • In order to see all of the cookies set: print_r($_COOKIE); • This will show all cookies currently contained in the cookie array

  34. More Cookies <?php setcookie("LoginName","Ciara"); setcookie("PreferredColor","Blue"); print("2 cookies were delivered.\n"); ?> <html> <head> <title>New Page 1</title> </head> <body> <a href="getcook.php">Move to get cookie page</a> </body> </html>

  35. <html> <head> <title>Cookie</title> </head> <body> <?php if (isset($_COOKIE["LoginName"])) { $loginName = $_COOKIE["LoginName"]; print("Received a cookie named as LoginName: ".$loginName."\n<br>"); } else { print("Did not received any cookie named as LoginName.\n<br>"); } print("All cookies received:\n<br>"); foreach ($_COOKIE as $name => $value) { print " $name = $value\n<br>"; } ?> </body> </html>

  36. <?php $Month = 2592000 + time(); //this adds 30 days to the current time setcookie("AboutVisit", date("F jS - g:i a"), $Month); ?> <html> <head> <title>Cookie Tracking</title> </head> <body> <?php if(isset($_COOKIE["AboutVisit"])) { $last = $_COOKIE["AboutVisit"]; echo "Welcome back! <br> You last visited on ". $last; } else { echo "Welcome to our site!"; } ?> </body> </html>

More Related