Vous êtes sur la page 1sur 3

Using Sessions

HTTP is a stateless protocol cannot tell the difference between request from different users i.e. When a user requests one page, followed by another, HTTP does not provide a way for us to tell that both requests came from the same user Idea of Session control is to be able to track a user during his visit to a website, a single session on a website can be used to track a user during his visit to a website If we can do this, we can easily support logging in a user and showing content according to his authorization level Sessions in PHP are driven by a unique session ID, a random number. This session ID is generated by PHP and stored on the clients computer for the lifetime of a session It can be either stored on a user's computer in a cookie or passed along the URLs The session ID acts as a key that allows you to register particular variables called session variables Session variables are stored on the server The session ID is the only information visible at the client's side Cookie is a small piece of information that scripts can store on a client-side machine. We can set a cookie on a user's machine Some browsers do not accept cookies and some users might have disabled cookies in their browsers, that is why PHP sessions uses a dual cookie/URL method PHP uses cookies by default with sessions. If possible, a

cookie will be set to store the session ID The other method it can use is adding the session ID to the URL A session is only active as long as the current clients browser is open Start a session Register session variables Use session variables De-register variables and destroy the session

Starting a Session

Before using a session in PHP you must start the session Sessions must be started on every page, in which you wish to access session variables Start sessions using the session_start() function. It checks to see if there is already a current session. If no session has been started yet, it will create one, providing access to the superglobal array, $_SESSION If the session already exists, the superglobal array, $_SESSION will load the registered session variables so that we can use them The session_start() function must come before any output to the browser

Registering Session Variables

Session variables are created or registered by simply setting an element in this array $_SESSION['myvar'] = This is a session; The session variable you have just created will be tracked until the session ends or until you manually unset it

Using Session Variables


Must start a session Then can access the variable via the $_SESSION super global array e.g as $_SESSION['myvar']

Unsetting a Session Variable and Destroying a Session

You can unset or destroy a session variable using the unset() function unset ($_SESSSION['myvar']) To kill a session use session_destroy()

Vous aimerez peut-être aussi