Sie sind auf Seite 1von 30

ARRAYS, COOKIES & SESSIONS Computer Science Dept

What is an Array?
An array can store one or more values in a single variable name. -Each element in the array is assigned its own ID so that it can be easily accessed. -$array[key] = value;

Three types of Arrays


1) Numeric Array 2) Associative Array 3) Multidimensional Array

1. Numeric Array
- A numeric array stores each element with a numeric ID key. ways to write a numeric array.
- $names = array("Peter","Quagmire","Joe");

Munually
Example: $names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe";

The ID can be used in a script


Example: <?php $names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe"; echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors"; ?>

Associative Arrays
An associative array, each ID key is associated with a value. -When storing data about specific named values, a numerical array is not always the best way to do it. -With associative arrays we can use the values as keys and assign values to them.

Using an array to assign an age to a person.


$ages = array(Brent"=>42, Andrew"=>25, "Joshua16=>); $ages[Brent'] = 42"; $ages[Andrew'] = 25"; $ages['Joshua'] = 16";

The Id can be used in a script


<?php $ages[Brent] = 42"; $ages[Andrew] = 25"; $ages[Joshua] = 16"; echo Brent is " . $ages[Brent] . " years old."; ?>

Multidimensional Arrays
- In a multidimensional array, each element in the main array can also be an array. - And each element in the sub-array can be an array, and so on.

Example
$families = array( "Griffin"=>array ( "Peter", "Lois", "Megan" ), "Quagmire"=>array ( "Glenn" ), "Brown"=>array ( "Cleveland", "Loretta", "Junior" ) );

Array ( [Griffin] => Array ( [0] => Peter [1] => Lois [2] => Megan ) [Quagmire] => Array ( [0] => Glenn ) [Brown] => Array ( [0] => Cleveland [1] => Loretta [2] => Junior ) )

Output
echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?";

Is Megan a part of the Griffin family?

COOKIES & SESSIONS

How to create variables storing values across php scripts calls?


. . .

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)

Different mechanisms of the same solution


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.

What is a Cookie?
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.

How to Create a Cookie


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

<?php setcookie("uname", $name, time()+36000); ?> <html> <body>

How to Retrieve a Cookie Value


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. <html> <body> <?php if (isset($uname)) echo "Welcome " . $uname . "!<br />"; else echo "You are not logged in!<br />"; ?> </body> </html>

How to Delete a Cookie


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.

What is a Session?
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 propagated in the URL.

How to Create a Session


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

How do Sessions work?


They are based on assigning each user a unique number, or session id. Even for extremely heavy use sites, this number can for all practical purposes can be regarded as unique. e.g. 26fe536a534d3c7cde4297abb45e275a

How do Sessions work?


This session id is stored in a cookie, or passed in the URL between pages while the user browses. The data to be stored (e.g. name, log-in state, etc.) is stored securely serverside in a PHP superglobal, and referenced using the session id.

Storing Session Data


The $_SESSION superglobal array can be used to store any session data. e.g. $_SESSION[name] = $name; $_SESSION[age] = $age;

How to Retrieve a Session Value


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']++; ?>

How to Delete a Session Value


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

Destroying a Session
Often not required, but if we want to destroy a session: // clear all session variables $_SESSION = array(); // delete the session cookie if there is one if (isset($_COOKIE[session_name()])) { setcookie(session_name(),'',time()-42000,'/'); } // destroy session session_destroy(); // avoid reusing the SID by redirecting // back to the same page to regenerate session header('Location: '.$_SERVER['PHP_SELF']);

Session Expiry
By default, PHP sessions expire:
after a certain length of inactivity (default 1440s), the PHP garbage collection processes deletes session variables. Important as most sessions will not be explicitly destroyed. If URL propagated, session id is lost as soon as navigate away from the site.

Long-term Sessions
Although it is possible to customize sessions so that they are maintained after the browser is closed, for most practical purposes PHP sessions can be regarded as short-term. Long-term session data (e.g. remember me boxes) is usually maintained by explicitly setting and retrieving cookie data.

Difference between Cookies and Sessions


Cookies Limited storage space Insecure storage client-side User controlled Sessions Practically unlimited space Reasonably securely stored server-side No user control

Das könnte Ihnen auch gefallen