Presentation is loading. Please wait.

Presentation is loading. Please wait.

First Name Last Name Please enter your logon information: John Submit Chen Web Server Login.php Web Server Hello John Chen Greetings. php Please enter.

Similar presentations


Presentation on theme: "First Name Last Name Please enter your logon information: John Submit Chen Web Server Login.php Web Server Hello John Chen Greetings. php Please enter."— Presentation transcript:

1

2 First Name Last Name Please enter your logon information: John Submit Chen Web Server Login.php Web Server Hello John Chen Greetings. php Please enter your logon information: John Submit Chen Hello Greetings. php I forget who you are!! First Name Last Name Without State Management With State Management

3 Server-Side State Management Client-Side State Management Management Application state Information is available to all users of a Web application Cookies Text file stores information to maintain state Session state Information is available only to a user of a specific session The ViewState property Retains values between multiple requests for the same page Database In some cases, use database support to maintain state on your Web site Query strings Information appended to the end of a URL

4  Application state is a global storage mechanism accessible from all pages in the Web application  Session state is limited to the current browser session  Values are preserved through the use of application and session variables  Scalability  ASP.NET session is identified by the SessionID string Web Server Client Computer Application and Session variables SessionI D

5  Uses cookies to maintain state  Persistent cookies  Temporary/ Non-persistent cookies  Less reliable than server-side state management options  User can delete cookies  Less secure than server-side state management options  Limited amount of information  Client-side restrictions on file sizes Web Server Client Computer Cookie s

6 While the configuration in this tutorial applies to ProdigyView, the concepts apply to normal cookies and sessions in php. You may use these concepts with these two php functions. session_set_cookie_params http://php.net/manual/en/function.session-set-cookie-params.php setcookie http://php.net/manual/en/function.setcookie.php

7 You can insert the content of one file into another file before the server executes it, with the require() function. The require() function is used to create functions, headers, footers, or elements that will be reused on multiple pages.

8 Client-server connection is not permanent => Cannot be saved in program memory There are many clients connecting simultaneously => Cannot be saved in file (you cannot identify clients as well sometimes)......

9  Cookies  Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users.  Sessions  Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site.

10 To maintain state means the ability to retain values of variables and to keep track of users who are logged into the system.

11   HTTP is a stateless protocol. This means that each request is handled independently of all the other requests and it means that a server or a script cannot remember if a user has been there before.   However, knowing if a user has been there before is often required and therefore something known as cookies and sessions have been implemented.

12  Cookies  Sessions  Passing [hidden] variables

13 Cookies is data the stored in the user’s browser. Unlike sessions, cookies will last if a user closes their browser. Cookies have a size limit set by the browser. Sensitive information should not be stored in the cookie. Stored on user’s computer

14 Cookies are simple text strings of the form of name=value which are stored persistently on the client’s machine. A URL is stored with each cookie and it is used by the browser to determine whether it should send the cookie to the web server. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests for a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

15  setcookie(name [,value [,expire [,path [,domain [,secure]]]]])  name = cookie name  value = data to store (string)  expire = UNIX timestamp when the cookie expires. Default is that cookie expires when browser is closed.  path = Path on the server within and below which the cookie is available on.  domain = Domain at which the cookie is available for.  secure = If cookie should be sent over HTTPS connection only. Default false.

16 The setcookie() function is used to create cookies. Note: The setcookie() function must appear BEFORE the tag. setcookie(name, [value], [expire], [path], [domain], [secure]); This sets a cookie named "uname" - that expires after ten hours. …

17  setcookie(‘name’,’Robert’)  This command will set the cookie called name on the user’s PC containing the data Robert. It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain). It will expire and be deleted when the browser is closed (default expire).

18  setcookie(‘age’,’20’,time()+60*60*24*30)  This command will set the cookie called age on the user’s PC containing the data 20. It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain). It will expire and be deleted after 30 days.

19  setcookie(‘gender’,’male’,0,’/’)  This command will set the cookie called gender on the user’s PC containing the data male. It will be available within the entire domain that set it. It will expire and be deleted when the browser is closed.

20   All cookie data is available through the superglobal $_COOKIE:  $variable = $_COOKIE[‘cookie_name’]  or  $variable = $HTTP_COOKIE_VARS[‘cookie_name’]; e.g.  $age = $_COOKIE[‘age’]

21  To access a cookie you just refer to the cookie name as a variable or use $_COOKIE array  Tip: Use the isset() function to find out if a cookie has been set. <?php if (isset($uname)) echo "Welcome ". $uname. "! "; else echo "You are not logged in! "; ?>

22 <?php $count++; setCookie(“count”, $count); ?> Welcome! You’ve seen this site

23   To remove a cookie, simply overwrite the cookie with a new one with an expiry time in the past…  setcookie(‘cookie_name’,’’,time()-6000)   Note that theoretically any number taken away from the time() function should do, but due to variations in local computer times, it is advisable to use a day or two.

24  -> Values of the text typed in user form is passed to other HTML and/or server side script is called parameter passing.  -> A session refers to all the connections that a single client might make to a server in the course of viewing any pages associated with a given application.[1]  -> Maintenance of user's state during session(e.g.login to logout) is called a Session Tracking.

25  Visible form parameters  Hidden form parameters  Cookies  Session  URL Rewriting

26 Methods of passing parameters with  GET (smaller data i.e.1024 bytes)  POST(bigger data, as well as file upload) PHP uses predefined variables  $_GET['varname']  $_POST['varname']

27 PHP provides a large number of predefined variables represent everything from external variables to built-in environment variables, last error messages to last retrieved headers to all scripts. Superglobals — Superglobals are built-in variables that are always available in all scopes $GLOBALS — References all variables available in global scope $_SERVER — Server and execution environment information $_GET — HTTP GET variables $_POST — HTTP POST variables $_FILES — HTTP File Upload variables

28 $_REQUEST — HTTP Request variables $_SESSION — Session variables $_ENV — Environment variables $_COOKIE — HTTP Cookies $php_errormsg — The previous error message $HTTP_RAW_POST_DATA — Raw POST data $http_response_header — HTTP response headers $argc — The number of arguments passed to script $argv — Array of arguments passed to script

29 Values of predefined variables can be seen with <?php phpinfo() ?>

30  The session support allows you to register arbitrary numbers of variables to be preserved across requests.  A visitor accessing your web site is assigned an unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.

31 Sessions are just like cookies, except they store the user’s data on the web server. Every request has a unique session id. Sessions are more reliable than cookies.

32 Sessions is information that relates to a user and is stored on the server. A session will no longer exist once the browser closes. Sessions do not have a size limit. Sensitive information should be stored in the session. User saves session information User retrieves session information

33 The session_start () function is used to create cookies. <?php session_start(); ?>

34 Register Session variable session_register('var1','var2',...); // will also create a session PS:Session variable will be created on using even if you will not register it! Use it <?php session_start(); if (!isset($_SESSION['count'])) $_SESSION['count'] = 0; else $_SESSION['count']++; ?>

35 ?php // start the session session_start(); // Get the user's input from the form $name = $_POST['name']; // Register session key with the value $_SESSION['name'] = $name; ?>

36  One of the standard examples used to demonstrate how a session works is the hit counter application.  The example of coding:  With above code, the counter will increases by 1 on each subsequent page load.  If two browser windows are open, and request the same page in each one, PHP will maintain and increment individual session counters for each browser instance.

37  In this example:- Required to log in. Then stored the login name and session start time as two session variables.  This information is used to display the total number of minutes the session has been active.

38 " method="post"> here to refresh the page."; } else { echo "ERROR: Please enter your name!"; } } else if (isset($_SESSION['name'])) { // if a previous session exists // calculate elapsed time since session start and now echo "Welcome back, ". $_SESSION['name']. ". This session was activated ". round((time() - $_SESSION['start']) / 60). " minute(s) ago. Click here to refresh the page."; } ?> session_starttimeroundtime

39  The session start time is recorded in $_SESSION['start'] with the time() function.  Then, the value stored in $_SESSION['start'] is compared with the most current value of time() to calculate and display an (approximate) display of elapsed time.  The call to session_start() must appear first, before any output is generated by the script.  This is because the PHP session handler internally uses in-memory cookies to store session data, and the cookie creation headers must be transmitted to the client browser before any output.

40  Every session has a unique session ID – used by PHP to keep track of different clients.  This session ID is a long alphanumeric string, which is automatically passed by PHP from page to page so that the continuity of the session is maintained.  Use the session_id() function, as in this simple example:

41  When the user shuts down the client browser and destroys the session, the $_SESSION array will be flushed of all session variables.  A session can also explicitly be destroy.  For example, when a user logs out - by calling the session_destroy() function.  Consider the given example below:-  Before calling a session_destroy() to destroy a session, session_start() is called first to recreate it.  $_SESSION is a superglobal – can use it inside and outside functions without needing to declare it as global first.

42  PHP offers a single function for cookie manipulation – setcookie().  This function allows a read and write of cookie files. setcookiemktime

43  The setcookie() function accepts six arguments: i. name: the name of the cookie ii. value: the value of the cookie iii. expires: the date and time at which the cookie expires iv. path: the top-level directory on the domain from which cookie data can be accessed v. domain: the domain for which the cookie is valid vi. secure: a Boolean flag indicating whether the cookie should be transmitted only over a secure HTTP connection  Cookie values are automatically sent to PHP from the client.  Then, converted to key-value pairs in the $_COOKIE variable, a superglobal array similar to $_SESSION.  Values can be retrieved using standard associative array notation.

44 " method="post"> Enter your email address: "> $days day(s) since last submission"; } ?> <?php }roundtime

45 else { // if form has been submitted // set cookies with form value and timestamp // both cookies expire after 30 days if (!empty($_POST['email'])) { setcookie("email", $_POST['email'], mktime()+(86400*30), "/"); setcookie("lastsave", time(), mktime()+(86400*30), "/"); echo "Your email address has been recorded."; } else { echo "ERROR: Please enter your email address!"; } } ?> setcookiemktimesetcookietimemktime

46  The value entered into the form is stored as a cookie called email.  It will automatically retrieved to pre-fill the form field on all subsequent requests.  The time at which the data was entered is stored as a second cookie, and used to calculate the time elapsed between successive entries.

47  As HTTP is stateless protocol Session Tracking must be maintained by programmers with following ways: Hidden form parameters Cookies Session URL Rewriting

48 Parameter is passed from 1 page to other which is not visible from user. Can be retrieved in PHP by  $_GET[“username”]  $_POST[“username”]

49 Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. Set Cookie  bool setcookie ( string $name string $value, int $expire=0, string $path, string $domain, bool $secure=false, bool $httponly=false)  setcookie(“username”,”ami”,time()+300); Read Cookie  $_COOKIE['name']

50 session_cache_expire — Return current cache expire session_cache_limiter — Get and/or set the current cache limiter session_commit — Alias of session_write_close session_decode — Decodes session data from a string session_destroy — Destroys all data registered to a session session_encode — Encodes the current session data as a string session_get_cookie_params — Get the session cookie parameters session_id — Get and/or set the current session id session_is_registered — Find out whether a global variable is registered in a session session_module_name — Get and/or set the current session module session_name — Get and/or set the current session name session_regenerate_id — Update the current session id with a newly generated one session_register — Register one or more global variables with the current session session_save_path — Get and/or set the current session save path session_set_cookie_params — Set the session cookie parameters session_set_save_handler — Sets user- level session storage functions session_start — Initialize session data session_unregister — Unregister a global variable from the current session session_unset — Free all session variables session_write_close — Write session data and end session

51 File: Page1.php <?php session_start(); echo 'Welcome to page #1'; $_SESSION['favcolor'] = 'green'; $_SESSION['animal'] = 'cat'; $_SESSION['time'] = time(); session_set_cookie_params(10,"/","sun.com",true, false); ?>

52 Filename Page2.php session_start(); echo 'Welcome to page #2 '; echo $_SESSION['favcolor']; // green echo $_SESSION['animal']; // cat echo date('Y m d H:i:s', $_SESSION['time']);?> session_unset ();//releasing session data Echo $_SESSION['time'];//no output

53 The Apache server’s mod_rewrite module gives the ability to transparently redirect one URL to another by modifying URL (i.e. re-writing), without the user’s knowledge. Used in situations:- – Pass some information to other page – redirecting old URLs to new addresses Or - cleaning up the ‘dirty’ URLs coming from a poor publishing system

54 Following line must be uncommented available in /etc/httpd/conf/httpd.conf file LoadModule rewrite_module modules/mod_rewrite.so URL Rewriting examples – http://localhost/ami/123 http://localhost/ami/123 – http://localhost/~ami/UrlRewrite.php?name=amichoks i http://localhost/~ami/UrlRewrite.php?name=amichoks i

55 <?php if(isset($_SERVER['PATH_INFO'])){ echo $_SERVER['PATH_INFO'];} else if(isset($_GET['username'])) { echo $_GET['username']; } ?>

56  It will expire or  Cookies must be deleted with the same parameters as they were set with. If the value argument is an empty string (""), and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client.

57  To remove a cookie from the client, setcookie() is called.  With the same syntax used to originally set the cookie, but an expiry date in the past.  This will cause the cookie to be removed from the client system.

58  session_unregister(´varname´); How to destroy a session:  session_destroy()

59 <?php // start the session session_start(); $_SESSION = array(); session_destroy(); if($_SESSION['name']) { print "The session is still active"; } else { echo "Ok, the session is no longer active! "; } ?>

60 The cookie path and session is path on your server that you cookie or session will be accessible. Example: If you make your cookie path ‘/store/products’, the cookie will only be available on ‘http://www.example.com/store/products/index.php’. Using ‘/’ will make the cookie or session available in any directory.

61 The cookie and session domain is the domain the cookie/session is available on. If your domain is www.example.com, setting you’re cookie/session to that domain will make is only accessible under www.example.com. If it was set to subdomain.example.com, it will only be available under subdomain.example.com..example.com www.example.com Setting the domain to ‘.example.com’ will make the session/cookie available under all subdomains.

62 Cookie Secure and Session Secure will ensure that your data for a session/cookie will only save over an https connection. It is up to you, the developer, to make sure the value is read only over an https connection.

63 In some situations, the requirement may be having this cookie only accessible from a http connection. Setting this value to true will ensure that the cookie/session will NOT be accessible through JavaScript, java(ex:.jar files) and other non-http/https protocols.

64  Can’t call setCookie() after output has been sent to the browser  Can’t have more than 20 cookies/server  Cookies ONLY persist until the browser closes UNLESS you specify an expiry date: set Cookie(“name”, $value, time() + 3600);

65 Cookie and sessions do not last forever and nor should they. A cookie can be set for years but the average person will probably switch computers every 4-5 years. When setting the amount of time a session/cookie will last, you are passing in the amount of seconds. So if you want the cookie/session to expire in 5 minutes, set it to ’60*5’;

66  cookies and sessions are two different ways of making data "persistent" on the client.  A session retains data for the duration of the session.  A cookie retains values for as long as you need it to.


Download ppt "First Name Last Name Please enter your logon information: John Submit Chen Web Server Login.php Web Server Hello John Chen Greetings. php Please enter."

Similar presentations


Ads by Google