PHP #4 : sessions & cookies

Post on 18-Jul-2015

349 views 0 download

Transcript of PHP #4 : sessions & cookies

PHP : Sessions & cookies

1. Les Superglobales

Définition

Les Superglobales sont des variables internes qui sont toujours disponibles, quel que soit le contexteSource : http://php.net

Les Superglobales

$GLOBALS -

$_SERVER-

$_GET-

$_POST-

$_FILES-

$_COOKIE-

$_SESSION-

$_REQUEST-

$_ENV

Maman comment afficher le contenu d’une superglobale ?

<?php var_dump($_POST); ?>

2. Session

Définition

Sessions allow the PHP script to store data on the web server that can be later used, even between requests to different PHP pages. Sessions end when the user closes the browser, or when the web server deletes the session information, or when the programmer explicitly destroys the session.

Source : http://en.wikibooks.org

Utilisation (1)

At the top of each PHP script that will be part of the current session there must be the function session_start(). It must be before the first output (echo or others) or it will result in an error "Headers already sent out".Source : http://en.wikibooks.org

Utilisation (2)

<?php session_start();

$_SESSION['prenom'] = "Jean"; $_SESSION['nom'] = "Michel";

?>

<?php session_start();

echo $_SESSION['prenom']; // Jean echo $_SESSION['nom']; // Michel ?>

page_1.php page_2.php

3. Cookies

Définition

Les cookies sont un mécanisme d'enregistrement d'informations sur le client, et de lecture de ces informations. Ce système permet d'identifier et de suivre les visiteurs.Source : http://php.net

Utilisation (1)

At the top of each PHP script that will be part of the current session there must be the function session_start(). It must be before the first output (echo or others) or it will result in an error "Headers already sent out".Source : http://en.wikibooks.org

Utilisation (2)

page_1.php page_2.php

<?php

echo $_COOKIE["TestCookie"]; /* Toto avant h +1 heure */

?>

<?php

setcookie( "TestCookie", 'toto', time()+3600); /* 1 heure */

?>

4. Mise en pratique

Exercice : En route pour l’école !

Créer la page « fin de quizz » avec l’affichage du score global de l’utilisateur. Ecrans disponibles ici : https://www.dropbox.com/sh/34xttwuv09xx07e/AABUFOxVwHRYHeUQQCBPmp9Ua?dl=0

Après 10 questions, l’utilisateur arrive sur la page « fin de quizz ».

La page « fin de quizz » indique si le résultat de l’utilisateur est son meilleur score de la journée.

Merci pour votre attention.

CréditsPerfect Chocolate Chip Cookies - Kimberly Vardeman http://www.flickr.com/photos/kimberlykv/4643536339/