Vous êtes sur la page 1sur 30

Actualité du cours

Programmation Web
http://eric.univ-lyon2.fr/jdarmont/?page_id=445
L3 MIASHS
Année 2019-2020
Jérôme Darmont http://eric.univ-lyon2.fr/jdarmont/?feed=rss2

https://twitter.com/darmont_lyon2 #webmiashs
http://eric.univ-lyon2.fr/jdarmont/
2 Programmation web Programmation web

1 2

Plan du cours Création de sites web dynamiques

 Objectifs du cours  Pages web générées à la demande


 Bases de PHP  À l’aide d’un langage de programmation
 PHP objet
 Interface PHP-bases de données
 Architecture MVC et gabarits
 Annexes
– Langage HTML5
openclassrooms.com
– Feuilles de style CSS3

3 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 4 Programmation web http://eric.univ-lyon2.fr/jdarmont/

3 4

Interfaçage avec une base de données Une multitude de langages

Tâches Langage

Structuration et contenu statique HTML

Présentation CSS

Contenu dynamique PHP ou autre


openclassrooms.com

Opérations sur la base de données SQL

5 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 6 Programmation web http://eric.univ-lyon2.fr/jdarmont/

5 6

1
Principe de séparation du code Des versions qui coexistent (1/2)
HTML 5
 Pourquoi ? HTML 1 XHTML 1.0
HTML 4 en XML
XHTML 5
– Maintenance facilitée HTML 2 Évolution de HTML 4
 Code plus lisible HTML+ Non XHTML 1.1
 La modification d’une tâche n’affecte pas les autres HTML3 standards
– Réutilisation de code
1990 1995 1997 2000 2001 2003 2008

 Comment ?
HTML 3.2
– Architecture MVC XHTML 2
HTML 4
– Gabarits (templates) Standards W3C
Évolution de XHTML 1
Abandonnée en 2009

7 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 8 Tim Berners-Lee Programmation web http://eric.univ-lyon2.fr/jdarmont/

7 8

Des versions qui coexistent (2/2) Nécessité de standardisation

PHP PHP 4  Par le World Wide Web Consortium (W3C)


Personal Home Page Zend engine
– Validateur de code HTML
PHP/FI PHP 5 – Validateur de code CSS
Objet

1995 1997 1998 2000 2004 2015  Par les concepteurs de PHP
– PHP Standards Recommendations (PSR)
PHP 3 PHP 7 – La majorité des bibliothèques devient objet
PHP Hypertext Processor Performance

Rasmus Lerdorf
9 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 10 Programmation web http://eric.univ-lyon2.fr/jdarmont/

9 10

Plan du cours Un langage de script « serveur »


Script exécuté sur le serveur
 Objectifs du cours <html>
 Bases de PHP <body>
<?php echo "Bonjour"; ?>
</html>
 PHP objet </body>

 Interface PHP-bases de données Page web avec script Serveur Web Client

 Architecture MVC et gabarits <html>


<body>
 Annexes Bonjour
</html>
– Langage HTML5 </body>

– Feuilles de style CSS3 Page web sans script

11 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 12 Programmation web http://eric.univ-lyon2.fr/jdarmont/

11 12

2
Syntaxe de base Variables et types

 Balises de début et de fin d’un script  Variables : préfixées par le caractère $


<?php ?>  PHP ne nécessite pas de déclaration explicite du type
– Ex. <?php echo "Bonjour"; ?> de variable ().

 Séparateurs d'instructions : ;  Types de données : Ex. d'affectation


– Nombres entiers : int, integer $i = 1;
 Commentaires – Nombres réels : real, double, float $pi = 3.14;
– Ex. // Toute une ligne (façon C++) – Chaînes de caractères : string $ch = "oui";
# Toute une ligne (façon Shell Unix)
 Conversion de type : "cast" comme en C
/* Plusieurs
lignes (façon C) */ – Ex. $ipi = (int) $pi; // $ipi est égal à 3

13 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 14 Programmation web http://eric.univ-lyon2.fr/jdarmont/

13 14

Tableaux Tableaux multidimensionnels

 Scalaires ou associatifs
 Possibilité de mélanger indices scalaires et associatifs
– Création par assignation des valeurs
– Ex. $tscalaire[0] = "Chaîne 0"; // Indiçage à partir de 0
$tscalaire[1] = "Chaîne 1"; – Ex. $matrice[0][0] = 2;
$tassociatif["Dupont"] = 30; $mscalassoc["Dupont"][0] = 30;

Fonctions associées : $matrice2 = array(



array(1, 0, 0), 1 0 0
– Initialisation : array(0, 1, 0),  
Ex. $notes_scal = array(10, 12.5, 15, 8); array(0, 0, 1));  0 1 0
$notes_assoc = array("Valeriia" => 16, "Vadim" => 12);
0 0 1
– Nombre d’éléments :  
Ex. $n = count($notes_s)
15 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 16 Programmation web http://eric.univ-lyon2.fr/jdarmont/

15 16

Constantes Opérateurs arithmétiques

 Variables d'environnement  Opérateurs d'affectation Exemples


– Ex. $_SERVER["PHP_SELF"] – Affectation simple : $a = 2;
$_SERVER["SERVER_NAME"]
– Affectation multiple : $a = $b = 2;
$_SERVER["HTTP_REFERER"]
$_SERVER["REMOTE_ADDR"] – Affectation + opération : $a += 2;
– Pré/post incrémentation/décrémentation :
 Constantes définies par l'utilisateur ++$a; --$a;
$a++; $a--;
– Ex. define("MA_CHAINE", "Valeur de MA_CHAINE");
define("PI", 3.14159265); – Affectation conditionnelle : $max = ($a > $b) ? $a : $b;

 Opérateurs arithmétiques : + - * / % (modulo)


17 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 18 Programmation web http://eric.univ-lyon2.fr/jdarmont/

17 18

3
Opérateurs de chaînes Opérateurs logiques

 Concaténation de chaînes de caractères : .  Opérateurs logiques


– Ex. $ch1 = $ch2 . $ch3; – ET : and ou &&
$ch1 .= $ch4; – OU : or ou ||
– OU exclusif : xor
 Caractères spéciaux dans les chaînes – NON : !
(échappement)
– Antislash : \\  Opérateurs de comparaison
– Dollar : \$ – Égalité/Différence : == !=
=== pour les booléens
– Guillemets : \"
– Inférieur/Supérieur : < >
– Inférieur ou égal/Supérieur ou égal : <= >=

19 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 20 Programmation web http://eric.univ-lyon2.fr/jdarmont/

19 20

Affichage Affichage d’éléments dynamiques


 Procédures prédéfinies
– Ex. echo "Bonjour !";
 Variables
– Ex. print("Bonjour !");
– Ex. echo "Chaîne concaténée = $ch";
– Ces deux procédures sont le seul moyen d'afficher quelque
chose dans le document HTML final.
– Affichage de tableau : print_r($my_array); // pour débogage
 Constantes et résultats de fonction
 Formatage : Utilisation des éléments HTML – Ex. echo "Valeur de Pi = " . PI;
echo "Carré de Pi = " . carre($pi);
– Ex. echo "<h1>TITRE</h1>"; // Attention, on mélange les langages !

 Saut de ligne dans le code source


– Ex. echo "<h1>TITRE</h1>\n";
21 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 22 Programmation web http://eric.univ-lyon2.fr/jdarmont/

21 22

Tests (1/2) Tests (2/2)

if (condition) {instructions} if ($a > $b) {


[elseif (condition) {instructions}] echo "A > B";
[else {instructions}] } else {
echo "A <= B";
}
– Ex. if ($a > $b) echo "A > B"; // Une seule instruction
if ($a > $b) echo "A > B";
if ($a > $b) { // Plusieurs instructions elseif ($a < $b) echo "A < B";
echo "A > B"; else echo "A = B";
$b = $a;
} if (un_booleen === true) echo "Vrai !";

23 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 24 Programmation web http://eric.univ-lyon2.fr/jdarmont/

23 24

4
Sélection par cas (1/2) Sélection par cas (2/2)
switch($ch) {
switch(variable) {cas} case "a":
echo "A";
– Ex. switch($i) { $ch = "A";
case 0: break;
echo "i = 0"; case "b":
break; echo "B";
$ch = "B";
case 1: break;
echo "i = 1"; case "c":
break; echo "C";
$ch = "C";
case 2: break;
echo "i = 2";
break; default: echo "Ni \"a\" ni \"b\" ni \"c\"";
} }
25 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 26 Programmation web http://eric.univ-lyon2.fr/jdarmont/

25 26

Boucles (1/2) Boucles (2/2)

 Tant que : while(condition) {instructions}  Pour : for (initialisation; condition; incrémentation) {


Ex. $i = 1;

instructions
while ($i <= 10) {
echo $i; }
$i++;
}
– Ex. for ($i = 1; $i< = 10; $i++) echo $i;

 Répéter tant que : do {instructions} while(condition)


– Ex. $i = 1;
do {
echo $i++;
} while ($i <= 10);

27 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 28 Programmation web http://eric.univ-lyon2.fr/jdarmont/

27 28

Parcours de tableau scalaire Parcours de tableau associatif

 Boucle "pour tout élément" foreach (tableau as clé => valeur) {


foreach (tableau as valeur) { instructions
instructions }
}
– Ex. $tab = array( "Rouge" => "#FF0000",
– Ex. $tab = array ("Rouge", "Vert", "Bleu"); "Vert" => "#00FF00",
"Bleu" => "#0000FF" );
foreach ($tab as $val) {
echo "Valeur courante : $val"; foreach ($tab as $cle => $val) {
} echo "Code de $cle : $val";
}
29 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 30 Programmation web http://eric.univ-lyon2.fr/jdarmont/

29 30

5
Inclusion de fichiers externes Sessions

 Fonction require() : Provoque une erreur fatale si le  Objectif : Stockage de variables lors de la navigation
fichier requis manque (interruption du script) sur plusieurs pages web successives
 Fonction include() : Provoque seulement un
avertissement (warning) si le fichier requis manque
 Évaluation des fichiers inclus en mode HTML  Utilisations courantes :
– Identification des visiteurs d'un site par login et mot de passe
 Aide à séparer le code PHP et HTML stockés dans une base de données
 Exemples (paramètre des fonctions : une URL) – Gestion du profil des utilisateurs
– require("biblio.class.php"); – …
– include("une_page_web.html");
– include('http://serveur.fr/pg.html');
31 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 32 Programmation web http://eric.univ-lyon2.fr/jdarmont/

31 32

Fonctions de session Variables de session

 session_start(); // Indique un environnement session  Tableau associatif de variables (ou de tableaux)


// Doit être dans toutes les pages $_SESSION[]
// Doit précéder tout entête HTML – Ex. $_SESSION["nomEtu"] = "Darmont";
$_SESSION["tabNotes"] = array(18, 19, 19.5, 20);

 session_id(); // Indique l’identifiant de la session  Supprimer une variable : unset()


 session_name(); // Indique le nom de la session – Ex. unset($_SESSION["tabNotes"]);

 Tester l’existence d’une variable : isset()


 session_destroy(); // Détruit la session – Ex. if (isset($_SESSION["nomEtu"])) echo "OK";
else echo "KO";
33 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 34 Programmation web http://eric.univ-lyon2.fr/jdarmont/

33 34

Exemple de session (1/5) Exemple de session (2/5)


<?php
<!DOCTYPE html> // session.inc.php
<!-- session-entete.inc.html --> // Affichages
<html lang="fr"> echo "<ul>";
<head> echo "<li>Identifiant de session : " . session_id() . "</li>";
<meta charset="utf-8" /> echo "<li>Nom de session : " . session_name . "</li>";
<title>Exemple de session</title> echo "<li>Variable de session nom : ";
</head> if (isset($_SESSION["nom"])) echo $_SESSION["nom"];
<body> else echo "indéfinie";
echo "</li>";
echo "<li>Variable de session prénom : ";
<!-- session-pied.inc.html --> if (isset($_SESSION["prenom"])) echo $_SESSION["prenom"];
</body> else echo "indéfinie";
</html> echo "</li>";
echo "</ul>";
35 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 36 ?> Programmation web http://eric.univ-lyon2.fr/jdarmont/

35 36

6
Exemple de session (3/5) Exemple de session (4/5)
<?php <?php
// session1.php // session2.php
session_start(); session_start();
require("session-entete.inc.html"); require("session-entete.inc.html");
require("session.inc.php"); require("session.inc.php");
// Action // Action
$_SESSION["nom"] = "Aitarab"; unset($_SESSION["prenom"]);
$_SESSION["prenom"] = "Sofiane"; ?>
?>
<a href="session3.php">Page suivante</a>
<a href="session2.php">Page suivante</a>
<?php
<?php require("session-pied.inc.html");
require("session-pied.inc.html"); ?>
?>

37 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 38 Programmation web http://eric.univ-lyon2.fr/jdarmont/

37 38

Exemple de session (5/5) Plan du cours


<?php
// session3.php  Objectifs du cours
session_start();
require("session-entete.inc.html");  Bases de PHP
require("session.inc.php");
// Action  PHP objet
session_destroy();
?>
 Interface PHP-bases de données
<a href="session1.php">Retour</a>  Architecture MVC et gabarits
<?php  Annexes
require("session-pied.inc.html");
– Langage HTML5
?>
– Feuilles de style CSS3

39 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 40 Programmation web http://eric.univ-lyon2.fr/jdarmont/

39 40

objet objet

Programmation impérative Programmation orientée objet

 Basée sur la logique du traitement  Basée sur la définition des données


 Utilise beaucoup les structures de contrôle  Modularité
– Boucles – Plus facile à développer et maintenir
– Tests  Abstraction
 Importance des structures de données – Permet de créer des types indéfinis dans le langage
– Plus facile à réutiliser
 Lisibilité et maintenabilité souvent inversement
proportionnelle à la taille du code  Spécialisation
– Évite la duplication du code d’objets similaires
41 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 42 Programmation web http://eric.univ-lyon2.fr/jdarmont/

41 42

7
objet objet

Notions de classe et d’objet Encapsulation

Concept de maison Classe


 Rassembler données (attributs) et traitements
MAISON (méthodes) dans une classe

 Seules les méthodes permettent de lire/écrire


les attributs d’un objet
maison moderne
maison ancienne

Objets de la  Protection des objets


classe Maison
43 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 44 Programmation web http://eric.univ-lyon2.fr/jdarmont/

43 44

objet

Exemple de classe Visibilité des attributs et méthodes

Visible par toute méthode, même extérieure à la


classe (notion d’interface)
Public

Attributs Un attribut ne devrait jamais être public !

Privé Visible uniquement par les méthodes de la classe

Méthodes Visible par les méthodes de la classe et de ses


Protégé
sous-classes (on y reviendra)

45 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 46 Programmation web http://eric.univ-lyon2.fr/jdarmont/

45 46

objet objet

Interface La classe Maison en PHP


<?php
class Maison {
// Attributs
private $nom;
protected $prix;
public $commentaire; // C’est pas bien !

// Méthodes
public function afficherNom() {
echo $this->nom; // $this est l’objet courant
}
public function changerPrix($nouveau_prix) {
$this->prix = $nouveau_prix;
cdn57.androidauthority.net
}
}
47 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 48 ?> Programmation web http://eric.univ-lyon2.fr/jdarmont/

47 48

8
objet objet

Instanciation Constructeur

<?php Méthode qui permet d’initialiser un objet


// Création d’objets
$maison_moderne = new Maison(); <?php
$maison_ancienne = new Maison(); class Maison { // suite

// Appel de méthodes // Constructeur


$maison_moderne->commentaire = "Trop chère !"; function __construct($nom) {
// Possible car commentaire est un attribut public (dangereux) $this->nom = $nom;
$this->prix = 200000;
$maison_ancienne->afficherNom(); $this->commentaire = "No comment";
}
$maison_moderne->changerPrix(350000); }
?> ?>
49 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 50 Programmation web http://eric.univ-lyon2.fr/jdarmont/

49 50

objet objet

Appel au constructeur Héritage


Superclasse
C’est implicite !
Sous-classe
<?php
// Création d’objets
$maison_moderne = new Maison("Maison de style");

$maison_ancienne = new Maison("Maison rénovée");


?>

 Cabane EST UNe Maison


 Cabane hérite des attributs et des méthodes de Maison
51 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 52 Programmation web http://eric.univ-lyon2.fr/jdarmont/

51 52

objet objet

La sous-classe Cabane en PHP Polymorphisme

<?php Redéfinition des méthodes héritées dans la sous-classe


class Cabane extends Maison {
// Attribut spécifique
private $surface;
}

// Instanciation
cabanon = new Cabane("Ma cabane au Canada");

// Appel des méthodes héritées Méthode surchargée


cabanon->changerPrix(5000);
?>

53 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 54 Programmation web http://eric.univ-lyon2.fr/jdarmont/

53 54

9
objet

Surcharge dans Cabane PHP Standards Recommendations (PSR)


<?php
class Cabane extends Maison {
// Attribut spécifique
 Recommandations pour améliorer l’interopérabilité
private $surface; des applications PHP
// Constructeur surchargé
function __construct($nom, $surface) {
parent::__construct($nom);  Tendent à devenir des standards
$this->surface = $surface;
}
// Méthode surchargée  Parmi celles qui sont validées :
public function changerPrix($prix, $surface) {
parent::changerPrix($prix); – PSR-1 : Basic Coding Standard
$this->surface = $surface; // Pas très approprié – PSR-2 : Coding Style Guide
} // C’est juste pour l’exemple
}
55 ?> Programmation web http://eric.univ-lyon2.fr/jdarmont/ 56 Programmation web http://eric.univ-lyon2.fr/jdarmont/

55 56

L’essentiel de PSR-1 L’essentiel de PSR-2 (1/2)

Balises PHP <?php ?> ou <?= ?> Code PHP En PSR-1

Encodage des caractères UTF-8 without BOM Sauts de ligne Unix

Longueur des lignes de code 80 caractères maxi de préférence


Nom de classes En StudlyCaps
Instructions Une seule par ligne
Constantes En MAJUSCULES
Indentation 4 espaces (pas de tabulation)
Noms de fonctions/méthodes En camelCase()
Retour à la ligne après {
Blocs de code
} seule sur une ligne

57 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 58 Programmation web http://eric.univ-lyon2.fr/jdarmont/

57 58

L’essentiel de PSR-2 (2/2) Plan du cours

Visibilité des attributs/méthodes Doit être déclarée  Objectifs du cours


Instructions/constantes PHP En minuscules  Bases de PHP
Paramètres de Pas d’espace avant la virgule  PHP objet
fonctions/méthodes Une espace après la virgule
 Interface PHP-bases de données
Appel de fonctions/méthodes Pas d’espace avant les ()
 Architecture MVC et gabarits
Une espace après l’instruction
 Annexes
Entre les (),
Structures de contrôle – Langage HTML5
pas d’espace après ( ni avant ),
mais une espace après ) – Feuilles de style CSS3

59 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 60 Programmation web http://eric.univ-lyon2.fr/jdarmont/

59 60

10
Généralités Michael Widenius
Bases de données, requêtes

 Principe : imbrication de requêtes SQL dans PHP  Base de données : ensemble de tables
+ formulaires HTML pour les mises à jour
 Table : ensemble d'attributs et leurs valeurs
 SGBD utilisé : MariaDB
– Ex. ETUDIANT (numetu, nom, prenom, datenaiss, note)
– SGBD relationnel multi-utilisateurs rapide et open-source
– 1995 : MySQL AB (v1-v5.0)
– 2008 : rachat de MySQL AB par Sun Microsystems (v5.1)  Interrogation simple
– 2010 : rachat de Sun Microsystems par Oracle (v5.5-v8.0) SELECT listeAttributs FROM table
– 2010 : MariaDB fork libre de MySQL (v5.2-v10.3) WHERE condition
Désormais utilisé dans de nombreuses distributions Linux – Ex. SELECT nom, prenom FROM etudiant WHERE note >= 10

61 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 62 Programmation web http://eric.univ-lyon2.fr/jdarmont/

61 62

Création de table Contraintes d’intégrité

 Création de table  Clé primaire : identifie de façon unique les n-uplets


CREATE TABLE nomTable (liste(attribut, type)) (lignes) de la table
– Mot-clé PRIMARY KEY après le type
 Types de données principaux
– Nombre entier : INT  Clé étrangère : attribut d’une table qui est clé primaire
– Nombre réel : FLOAT dans une autre table
– Chaîne de caractères : VARCHAR(taille) – Création d’une contrainte après la définition des attributs
– Date : DATE CONSTRAINT nomContrainte
FOREIGN KEY(cléEtrangère)
REFERENCES tableRéférencée(cléPrimaire)

63 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 64 Programmation web http://eric.univ-lyon2.fr/jdarmont/

63 64

Exemple de création de table Mises à jour

 Insertion d'un n-uplet


CREATE TABLE etudiant ( numetu INT PRIMARY KEY, INSERT INTO nomTable VALUES (listeValeurs)
nom VARCHAR(50), – Ex. INSERT INTO etudiant VALUES (123, 'Darmont', 'Jérôme', '15-01-1972', 15.5, 4001)
prenom VARCHAR(100),
datenaiss DATE,  Modification d'un n-uplet
notemoy FLOAT, UPDATE nomTable SET attribut = valeur WHERE condition
numcarte INT, – Ex. UPDATE etudiant SET note = 20 WHERE numetu = 123
CONSTRAINT carteFK
FOREIGN KEY(numcarte)  Suppression d'un n-uplet
REFERENCES carte_izly(numcarte) DELETE FROM nomTable WHERE condition
)
– Ex. DELETE FROM etudiant WHERE numetu = 123

65 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 66 Programmation web http://eric.univ-lyon2.fr/jdarmont/

65 66

11
PDO

Jointure PHP Data Objects (PDO)

 Requête multi-table  Accès unifié à différents SGBD


SELECT listeAttributs – Remplace les API précédentes (ex. API PHP-
FROM table1, table2, … tableN MySQL), obsolètes et vouées à disparaître
WHERE conditionJointureT1T2

AND conditionJointureTN-1TN
 Préparation des requêtes
– Performance lors d’exécutions multiples
– Ex. SELECT * – Sécurité (notamment contre les injections de code)
FROM etudiant, carte_izly
WHERE etudiant.carte = carte_izly.numcarte  Gestion des exceptions (erreurs)
67 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 68 Programmation web http://eric.univ-lyon2.fr/jdarmont/

67 68

PDO PDO

Connexion à une BD Exécution d’une requête

 Connexion
$pdo = new PDO(idServeurBD, login, motDePasse);  Préparation de la requête
– idServeurBD = pilote:host=serveur;dbname=nomBD $res = $pdo->prepare(requêteSQL)
– Ex. – Ex. $res = $c->prepare("select nom, prenom from etudiant");
$c = new PDO("mysql:host=localhost;dbname=darmont", "darmont", "x");
 Exécution de la requête
 Gestion des erreurs – Ex. $res->execute();
try { instructions } catch () { traitementDesErreurs }
– Ex. try {  Accès au résultat de la requête (ligne par ligne)
// Connexion – Ex. foreach($res as $ligne)
} catch (PDOException $erreur) {
echo $erreur->getMessage() ; echo $ligne["nom"] . " " . $ligne["prenom"];
}
69 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 70 Programmation web http://eric.univ-lyon2.fr/jdarmont/

69 70

PDO PDO

Résultat intégral Requêtes paramétrées

 Chargement complet du résultat de la requête


en mémoire // Exemple avec paramètres anonymes
– Rapide, utile quand on utilise des gabarits (templates) $res = $c->prepare("select nom, prenom from etudiant
– À éviter lorsque le résultat est volumineux where datenaiss > ? and note >= ?");

 Exemple $res->execute(["2018-01-01", 10]);


$res = $c->prepare("select nom, prenom from etudiant");
// Les paramètres doivent être passés dans l’ordre
$res->execute();
$data = $res->fetchAll(PDO::FETCH_ASSOC);
foreach($data as $ligne)
echo $ligne["nom"] . " " . $ligne["prenom"];
71 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 72 Programmation web http://eric.univ-lyon2.fr/jdarmont/

71 72

12
PDO PDO

Requêtes paramétrées multiples (1/2) Requêtes paramétrées multiples (2/2)

// 1re insertion
// Exemple avec paramètres nommés $id = 800;
$res = $c->prepare("insert into ETUDIANT $nom = "Bentayeb";
values (:id, :nom, :prenom, NULL, NULL, NULL)"); $prenom = "Fadila";
$res->execute();
// Liaison des paramètres
$res->bindParam(":id", $id); // 2e insertion
$res->bindParam(":nom", $nom); $id = 810;
$res->bindParam(":prenom", $prenom); $nom = "Harbi";
$prenom = "Nouria";
$res->execute();

73 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 74 Programmation web http://eric.univ-lyon2.fr/jdarmont/

73 74

PDO

Exemple complet Formulaires


try {
// Connexion  Formulaires : permettent la saisie de données dans une
$c = new PDO("mysql:host=localhost;dbname=darmont", "darmont", "x"); page web
$c->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Requête d’interrogation
$res = c->prepare("select nom, prenom from etudiant");
$res->execute();  Définition : <form> </form>
foreach($res as $ligne) – Attribut action : URL de la page PHP à exécuter après validation
echo $ligne["nom"] . " " . $ligne["prenom"]; du formulaire
echo $res->rowCount() . " résultat(s)";
// NB : rowCount() fonctionne aussi avec les requêtes de mise à jour
– Attribut method : méthode de transmission des données (valeurs
possibles : get et post)
} catch (PDOException $erreur) { // Gestion des erreurs – Attribut enctype : type d'encodage (par défaut application/x-
echo $erreur->getMessage(); www-form-urlencoded ou multipart/form-data pour envoyer des
} fichiers)

75 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 76 Programmation web http://eric.univ-lyon2.fr/jdarmont/

75 76

Méthodes de transmission des données Champs (1/5)

 Différence entre les méthodes get et post  Saisie dans un formulaire : <input />
– Attribut obligatoire : name, nom de la variable
– get : apparition des valeurs saisies en paramètres de l'URL de
la page action  Champ texte : <input type="text" size="" />
– post : . valeurs saisies cachées – Ex. <input type="text" name="nom" size="30" />
. quantité de données possible plus importante
 Suggestion de valeurs : <datalist>…</datalist>
 Exemple
<form action="ajout_etu.php" method="post">…</form> – Ex. <datalist id="prop_noms">
<option value="Dupond">
 Structure d'un formulaire : ensemble de zones de <option value="Durand">
saisie (groupes de champs) <option value="Martin">
 Groupe de champs : <fieldset> </fieldset> </datalist>
<input type="text" name="nom" list="prop_noms" />
77 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 78 Programmation web http://eric.univ-lyon2.fr/jdarmont/

77 78

13
Champs (2/5) Champs (3/5)

 Vérification syntaxique : expressions régulières  Bouton radio : <input type="radio" value="" />
– Ex. <input type="email" pattern="[^ @]*@[^ @]*" /> – Ex.
Homme : <input type="radio" name="genre" value="H" />
 Champ mot de passe : <input type="password" /> Femme : <input type="radio" name="genre" value="F" />
– Ex. <input type="password" name="passwd" size="8" />
 Case à cocher : <input type="checkbox" />
 Champ caché : <input type="hidden" value="" />
– Ex.
– Ex. <input type="hidden" name="numetu" value="10" />
choix 1 : <input type="checkbox" name="choix1" />
choix 2 : <input type ="checkbox" name="choix2" />
 Fichier : <input type="file" />
– Ex. <input type="file" name="Fichier_téléchargé" />
79 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 80 Programmation web http://eric.univ-lyon2.fr/jdarmont/

79 80

Champs (4/5) Champs (5/5)

 Boutons de commande  Liste déroulante : <select> </select>


– Attribut type = submit | reset : validation ou réinitialisation du
formulaire – Attribut name : nom de la variable choix
– Attribut value : légende du bouton – Élément <option> </option> : objet de la liste
– Ex. <input type="submit" name="Valider" value="Valider" /> – Attribut selected de <option> : choix par défaut
<input type="reset" name="Annuler" value="Annuler" /> – Ex. <select name="annee">
<option>Licence</option>
 Zone de texte long : <textarea> </textarea> <option selected="selected">M1</option>
– Attribut name : nom de la zone de texte <option>M2 professionnel</option>
<option>M2 recherche</option>
– Attributs rows et cols : nombre de lignes / colonnes
</select>
– Ex. <textarea name="texte" rows="10" cols="60">
</textarea>
81 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 82 Programmation web http://eric.univ-lyon2.fr/jdarmont/

81 82

Accessibilité Exemple complet de formulaire


<form action="ajout_etu.php" method="post">
 Description de champ : <label> </label> <fieldset>
– Ex. <label for="id_nom">Nom</label> <p> Nom : <input type="text" name="nom" size="50" /> </p>
<input type="text" id="id_nom" name="nom" /> <p> Âge : <input type="text" name="age" size="2" /> </p>
<p> Année : <select name="annee">
<option>Licence</option>
 Légende de zone de saisie : <legend> </legend> <option selected="selected">M1</option>
– Ex. <fieldset> <option>M2</option>
<legend>État civil de l'étudiant</legend> </select> </p>
… <input type="hidden" name="action" value="ajout" />
</fieldset>
<p> <input type="reset" value="Annuler" />
<input type="submit" value="Valider" /> </p>
</fieldset>
83 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 84 </form> Programmation web http://eric.univ-lyon2.fr/jdarmont/

83 84

14
PDO

Exploitation des données d'un formulaire Mise à jour d'une base de données

 Dans la page cible (Ex. ajout_etu.php) <?php // Suite de l'exemple : document ajout_etu.php
– Tableaux associatifs $_GET[ ] et $_POST[ ] $c = new PDO("mysql:host=localhost;dbname=darmont",
– Permettent d'accéder aux valeurs transmises par les
méthodes get et post des formulaires, respectivement "darmont", "x");

 Exemple $resultat = $c->prepare("insert into etudiant values (?, ?, ?)");


<?php $resultat->execute([ $_POST["nom"],
echo "L'étudiant " . $_POST["nom"];
echo " a " . $_POST["age"] . " ans"; $_POST["age"],
echo " et est en " . $_POST["annee"]; $_POST["annee"] ]);
?>
if ($resultat->rowCount() > 0)
 Cas particuliers : case à cocher (valeur "on" si cochée) echo "Etudiant.e ajouté.e";
et fichiers
?>
85 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 86 Programmation web http://eric.univ-lyon2.fr/jdarmont/

85 86

Téléchargement de fichier (1/2) Téléchargement de fichier (2/2)

 Variables disponibles dans la page cible


 Étape 1 : formulaire dans une page HTML – $_FILES["monfichier"]["name"] : nom original du fichier
– Ex.
– $_FILES["monfichier"]["type"] : type du fichier
<form action="telechargement.php" method="post"
enctype="multipart/form-data" /> – $_FILES["monfichier"]["size"] : taille du fichier
<fieldset> – $_FILES["monfichier"]["tmp_name"] : nom temporaire du fichier sur la
<input type="hidden" name="MAX_FILE_SIZE" value="50000" /> machine serveur
Fichier : <input name="monfichier" type="file" />
<input type="submit" value="Télécharger" />  Exemple de code dans la page telechargement.php
</fieldset> $destination = "/home/jd/public_html/" . $_FILES["monfichier"]["name"];
</form> $res = move_uploaded_file($_FILES["monfichier"]["tmp_name"],
$destination);
 Étape 2 : traitement à l'aide de PHP if ($res) echo "Fichier téléchargé avec succès";
else echo $_FILES["monfichier"]["error"];
87 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 88 Programmation web http://eric.univ-lyon2.fr/jdarmont/

87 88

Trygve Reenskaug
1978

Plan du cours Principe de MVC


Accès à la BD

 Objectifs du cours
 Bases de PHP Calcul

 PHP objet
 Interface PHP-bases de données
 Architecture MVC et gabarits
Affichage

 Annexes
– Langage HTML5
– Feuilles de style CSS3
openclassrooms.com

89 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 90 Programmation web http://eric.univ-lyon2.fr/jdarmont/

89 90

15
Modèle Vue

 Gestion des données


 Présentation des résultats
– Base de données ou fichiers
 Interaction avec l’utilisateur·trice
 Ensemble de classes et de méthodes
– Mises à jour (ajout/modification/suppression)
 Langages
– Interrogation
– HTML uniquement si utilisation de gabarits
 Langages – Instructions PHP simples sinon
– PHP
– SQL
91 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 92 Programmation web http://eric.univ-lyon2.fr/jdarmont/

91 92

Contrôleur MVC ≠ 3-tiers

 Analyse des requêtes de l’utilisateur·trice  Architecture 3-tiers  Architecture MVC


– Couches – La vue peut consulter
 Interrogation ou mise à jour du modèle
le modèle
 Modification de la vue Présentation sans passer par
le contrôleur
(lecture uniquement)
 Langage Traitement
– PHP
Accès aux
données

93 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 94 Programmation web http://eric.univ-lyon2.fr/jdarmont/

93 94

Cas pratique (1/2) Cas pratique (2/2)


<!DOCTYPE html>
<?php
<html lang="fr"> require("connect.inc.php");
$c = new PDO("mysql:host=$host;dbname=$dbname", $login, $password);
<head> $res = $c->prepare("SELECT * FROM matiere");
<meta charset="utf-8" /> $res->execute();
<title>Exemple d'application non-MVC</title> foreach ($res as $ligne)
<!-- Seul effort de séparation du code : --> echo "<tr> <td>" . $ligne["codemat"] . "</td> <td>" . $ligne["libelle"]
<link rel="stylesheet" href="tableau.css" /> . "</td> <td>" . $ligne["coef"] . "</td> </tr>\n";
</head> ?>

<body> </table>
<table> </body>
<caption>Liste des matières</caption> </html>
<tr> <th>codemat</th> <th>libelle</th> <th>coef</th> </tr>
95 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 96 Programmation web http://eric.univ-lyon2.fr/jdarmont/

95 96

16
Découpage : modèle Découpage : vue (1/2)
<?php // modele-o.inc.php
class Modele {
private $idc; <!DOCTYPE html>
private function connexion() { <!-- vue.inc.php -->
require("connect.inc.php");
$this->idc = new PDO("mysql:host=$host; <html lang="fr">
dbname=$dbname", $login, $password);
} <head>
public function lireMatieres() { <meta charset="utf-8" />
$this->connexion(); <title>Exemple d'application MVC</title>
$res = $this->idc->prepare("SELECT * FROM matiere"); <link rel="stylesheet" href="tableau.css" />
$res->execute; </head>
return $res;
}
}
97 ?> Programmation web http://eric.univ-lyon2.fr/jdarmont/ 98 Programmation web http://eric.univ-lyon2.fr/jdarmont/

97 98

Découpage : vue (2/2) Découpage : contrôleur

<body>
<table>
<caption>Liste des matières</caption>
<?php // controleur-o.php
<tr> <th>codemat</th> <th>libelle</th> <th>coef</th> </tr>
<?php foreach ($res as $ligne) { ?>
<tr> require("modele-o.inc.php");
<td><?php echo $ligne["codemat"] ?></td> $mod = new Modele();
<td><?php echo $ligne["libelle"] ?></td>
<td><?php echo $ligne["coef"] ?></td> $res = $mod->lireMatieres();
</tr>
<?php } ?> require("vue.inc.php");
</table> ?>
</body>
</html>
99 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 100 Programmation web http://eric.univ-lyon2.fr/jdarmont/

99 100

TEMPLATE TEMPLATE

Gabarits Exemple de gabarit

 Objectifs :
– Encore séparation du code PHP et HTML <table> <!-- gab1.tpl.html -->
<caption>Variables simples</caption>
– Partage de gabarits entre plusieurs applications web
<tr>
<th>Nom</th>
<th>Prénom</th>
</tr>
<tr>
<td>{nom}</td>
<td>{prenom}</td>
</tr>
</table>
phpcodeur.net
101 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 102 Programmation web http://eric.univ-lyon2.fr/jdarmont/

101 102

17
TEMPLATE TEMPLATE

Affectation de variables à un gabarit Gabarit avec bloc de répétition


// Bibliothèque template simple et libre du phpBB Group
require("template.class.php");
<table> <!-- gab2.tpl.html -->
<caption>Bloc de répétition</caption>
// Lecture des données <tr>
$res = $c->prepare("select nom, prenom from etudiant where numetu = ?"); <th>Nom</th>
$res->execute([110]); <th>Prénom</th>
$ligne = $res->fetch(); </tr>
<!-- BEGIN etu -->
// Mise en œuvre du gabarit <tr>
$gab1 = new Template("./"); // Paramètre : chemin d'accès aux gabarits
<td>{etu.nom}</td>
$gab1->set_filenames(array("body1" => "gab1.tpl.html")); // Nom du fichier gabarit
// Assignation des variables
<td>{etu.prenom}</td>
$gab1->assign_vars(array("nom" => $ligne["nom"], </tr>
"prenom" => $ligne["prenom"])); <!-- END etu -->
$gab1->pparse("body1"); // Affichage des données </table>
103 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 104 Programmation web http://eric.univ-lyon2.fr/jdarmont/

103 104

TEMPLATE TEMPLATE

Mise en œuvre d’un bloc de répétition Blocs imbriqués

require("template.class.php");
<table> <!-- gab3.tpl.html -->
// Lecture des données
<caption>Blocs imbriqués</caption>
$res = $c->prepare("select nom, prenom from etudiant");
$res->execute(); <!-- BEGIN etu -->
<tr>
// Mise en œuvre du gabarit <!-- BEGIN attribut -->
$gab2 = new Template("./"); <td>{etu.attribut.valeur}</td>
$gab2->set_filenames(array("body2" => "gab2.tpl.html")); <!-- END attribut -->
foreach($res as $ligne) </tr>
$gab2->assign_block_vars("etu", <!-- END etu -->
array( “nom" => $ligne["nom"],
</table>
“prenom" => $ligne["prenom"] ));
$gab2->pparse('body2');

105 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 106 Programmation web http://eric.univ-lyon2.fr/jdarmont/

105 106

TEMPLATE TEMPLATE

Mise en œuvre de blocs imbriqués Gabarit dans l’application MVC exemple (1/4)

<?php // modele-og.inc.php
require("template.class.php"); class Modele {
// Lecture des données private $idc;
private function connexion() {
$res = $c->prepare("select * from etudiant"); // Comme dans mode-o.inc.php
$res->execute(); }
$data = $res->fetchAll(PDO::FETCH_ASSOC); public function lireMatieres() {
// Comme dans mode-o.inc.php
// Mise en œuvre du gabarit }
$gab3 = new Template("./"); public function afficherMatieres($data) {
$gab = new Template("./");
$gab3->set_filenames(array("body3" => "gab3.tpl.html")); $gab->set_filenames(array("body" => "vue.tpl.html"));
foreach($data as $ligne) { foreach($data as $ligne)
$gab3->assign_block_vars("etu", array("rien" => "")); // Boucle sur les <tr> $gab->assign_block_vars("matiere",
foreach ($ligne as $val) array( "codemat" => $ligne["codemat"],
"libelle" => $ligne["libelle"],
$gab3->assign_block_vars("etu.attribut", array("valeur" => $val)); "coef" => $ligne["coef"] ));
} $gab->pparse('body');
$gab3->pparse('body3'); }
}
107 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 108 ?> Programmation web http://eric.univ-lyon2.fr/jdarmont/

107 108

18
TEMPLATE TEMPLATE

Gabarit dans l’application MVC exemple (2/4) Gabarit dans l’application MVC exemple (3/4)

<!DOCTYPE html>
<html lang="fr"> <!-- vue.tpl.html (vue et gabarit) -->
<!-- BEGIN matiere -->
<head>
<tr>
<meta charset="utf-8" />
<td>{matiere.codemat}</td>
<title>Exemple d'application MVC</title>
<td>{matiere.libelle}</td>
<link rel="stylesheet" href="tableau.css" />
<td>{matiere.coef}</td>
</head>
</tr>
<body>
<!-- END matiere -->
<table>
</table>
<caption>Liste des matières</caption>
</body>
<tr> <th>codemat</th> <th>libelle</th> <th>coef</th> </tr>
</html>

109 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 110 Programmation web http://eric.univ-lyon2.fr/jdarmont/

109 110

TEMPLATE

Gabarit dans l’application MVC exemple (4/4) Plan du cours

 Objectifs du cours
<?php // controleur-og.php  Bases de PHP
require("template.inc.php");
require("modele-og.inc.php");
 PHP objet
 Interface PHP-bases de données
$mod = new Modele();
$res = $mod->lireMatieres();  Architecture MVC et gabarits
$mod->afficherMatieres($res);  Annexes
?>
– Langage HTML5
– Feuilles de style CSS3

111 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 112 Programmation web http://eric.univ-lyon2.fr/jdarmont/

111 112

Généralités Pourquoi des standards ? (1/2)

 HTML : HyperText Markup Language  Éviter la "balkanisation du Web" des années 1990
– Liens hypertextes  Interopérabilité et portabilité (tablettes, téléphones
– Langage à base de balises mobiles…)

 Objectif : publier sur le Web des documents formatés  Accessibilité aux personnes handicapées
 Réduction des coûts de développement
 Développé par Tim Berners-Lee au CERN (Suisse)
 Exploitation de la technologie XML (vers le Web
 Standardisé par le World Wide Web Consortium (W3C) sémantique / Web 3.0)
– Exemple : moteurs de recherche (personnalisation, suggestions,
résumé d’informations…)
113 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 114 Programmation web http://eric.univ-lyon2.fr/jdarmont/

113 114

19
Pourquoi des standards ? (1/2) Éléments, balises et attributs

 Contrôle qualité (validation des pages Web)  Élément : nom, notion abstraite
– Ex. Document HTML : html
 Réduction considérable du volume des documents
 Balise : forme concrète d'un élément
 Référencement efficace dans les moteurs de – Ex. de balise ouvrante : <html>
recherche – Ex. de balise fermante : </html>

 Pérennité des documents  Attribut : propriété d'un élément (nom, valeur)


– Ex. <a href="http://www.univ-lyon2.fr">
 Rétrocompatibilité avec les anciens navigateurs
Nom Valeur
115 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 116 Programmation web http://eric.univ-lyon2.fr/jdarmont/

115 116

Règles d'écriture XHTML Squelette d'un document HTML


<!DOCTYPE html> <!-- Identification du type du document
 Les noms des balises doivent être écrits en minuscules. (note : ceci est un commentaire) -->
<html lang="fr">
 Toute balise ouverte doit être fermée.
 Les chevauchements entre balise sont interdits <head>
(documents bien formés). <!-- En-tête -->
</head>
 Les noms des attributs doivent être écrits en
minuscules. <body>
<!-- Corps du document -->
 Les valeurs des attributs doivent être entre guillemets </body>
doubles.
</html>
117 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 118 Programmation web http://eric.univ-lyon2.fr/jdarmont/

117 118

En-tête Exemple d'en-tête


<head>
 Informations qui ne sont pas affichées mais qui sont <!-- Jeu de caractères universel -->
utilisées à des fins diverses <meta charset="utf-8" />
 Titre : <title>…</title>
<!-- Autres métadonnées -->
 Métadonnées : <meta /> <meta name="Author" content="Jérôme Darmont" />
– Ex. Jeu de caractères, auteur, mots-clés, description de la <meta name="Keywords" content="Enseignement,Informatique" />
page… <meta name="Description" content="Exemple de page HTML" />

 Note : Une balise vide peut se noter <balise></balise> <!-- Titre -->
ou <balise />, au choix. <title>Exemple de page HTML</title>
</head>
119 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 120 Programmation web http://eric.univ-lyon2.fr/jdarmont/

119 120

20
Optimisation des performances Corps du document

 Préchargement DNS  Éléments de structuration du document


– Ex. <link rel="dns-prefetch" href="//platform.twitter.com"> – Invisibles
– Permettent la mise en page ultérieure du document
 Préchargement de lien – Permettent la génération automatique, par ex., d’une table des
– Ex. <link rel="prefetch" href="http://darmont.me/hello.html" /> matières, des figures, etc.
– Ex. <link rel="prefetch" href="http://darmont.me/picture.png" />
 Éléments qui apparaissent explicitement à l’affichage
 Prérendu de page – Texte
– Ex. <link rel="prerender" href="http://darmont.me/hello.html" /> – Images
– …

121 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 122 Programmation web http://eric.univ-lyon2.fr/jdarmont/

121 122

Structuration du document Titres, paragraphes, séparateurs

 Contenu principal : <main> </main>  Titres (headings) : Six niveaux notés h1 à h6


– Ex. <h1>Titre de niveau 1</h1>
 Section : <section> </section>
 Article : <article> </article>  Paragraphes (séparés entre eux par un espace)
 Encadré : <aside> </aside> – Ex. <p>Ceci est un paragraphe</p>
 Entête : <header> </header>
 Pied de page : <footer> </footer>  Séparateurs :
– Retour à la ligne (sans espace) : <br />
 Menu de navigation : <nav> </nav> – Ligne horizontale : <hr />
 Boîte de dialogue : <dialog> </dialog>

123 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 124 Programmation web http://eric.univ-lyon2.fr/jdarmont/

123 124

Autres blocs de texte prédéfinis Formatage de texte

 Texte « appuyé » : <strong>…</strong>


 Adresse
– Ex. <address>5 av. P. Mendès-France </address>  Emphase : <em>…</em>
 Surlignage : <mark>…</mark>
 Citation  Police « machine à écrire » : <code>…</code>
– Ex. <blockquote>Mignonne allons voir</blockquote>  En indice : <sub>…</sub>
 En exposant : <sup>…</sup>
 Texte préformaté  Caractères spéciaux :
– Ex. <pre>Le formatage sera < : &lt; & : &amp;
conservé > : &gt; " : &quot;
espace insécable : &nbsp;
à l'écran</pre>
125 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 126 Programmation web http://eric.univ-lyon2.fr/jdarmont/

125 126

21
Imbrication des balises Liens hypertextes

<!-- Exemple -->  Forme générale : <a href="URL">libellé</a>


<header><h1>Présentation du master IDSM</h1></header>  URL : Uniform Resource Locator
<article> – Absolue (adresse complète)
<p>L'<strong>Université Lumière Lyon 2</strong> et Ex. http://www.hdeu.edu.ua
l’<strong>Université Nationale d’Économie de Kharkiv</strong> ftp://ftp.ciril.fr
proposent une formation d'excellence (<em><strong>double diplôme mailto:jerome.darmont@univ-lyon2.fr
de master</strong></em>) en <em>informatique et
statistique</em>.<br /> Ces domaines se développent rapidement, – Relative (à partir du répertoire courant)
tant au niveau de la recherche que dans l'industrie, et offrent de Ex. page_suivante.html
nombreux emplois.</p> rep/page_dans_repertoire.html
</article> – Exemple : <a href="http://www.univ-lyon2.fr">Université Lyon 2</a>

127 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 128 Programmation web http://eric.univ-lyon2.fr/jdarmont/

127 128

Ancres Images

 Permettent un lien vers un endroit précis dans une  Formats reconnus :


page Web
 Balise : <img src="URL" alt="description" title="title" />
 Définition dans une page : attribut id – Ex. <img src="lyon2-logo.jpg" alt="Logo UL2" title="Logo UL2" />
– Ex. <h1 id="menu">MENU</h1> – Ex. <img src="http://eric.univ-lyon2.fr/~jdarmont/wp-
content/uploads/2015/02/lyon2-logo2014.jpg" alt="Logo UL2" alt="Logo UL2" />

 Référence depuis la même page


 Lien sur une image
– Ex. <a href="#menu">Aller au menu</a> – Ex.
<a href="http://www.univ-lyon2.fr">
 Référence depuis une autre page <img src="lyon2-logo.jpg" alt="UL2" title="UL2" />
</a>
– Ex. <a href="page.html#menu">Retour menu</a>
129 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 130 Programmation web http://eric.univ-lyon2.fr/jdarmont/

129 130

Multimédia Figures
 Sons : élément <audio> </audio>  Élément de structuration (comme section, article…)
 Vidéos : élément <video> </video>  Balises : <figure> </figure>
 Attributs communs  Légende : <figcaption> </figcaption>
– src : URL du contenu  Exemple :
– controls : affiche les contrôles du lecteur multimédia <figure>
– autoplay : démarrage dès que possible <img src="tim-berners-lee.jpg" alt="Photo Tim BL" />
– loop : en boucle <video src="test.ogg" controls="controls" muted="muted">
Le format .ogg n'est pas supporté.
– muted : sans son
</video>
<audio src="chord.wav" controls="controls">
 Exemple
Le format .wav n'est pas supporté.
 <audio src="test.mp3" controls="controls" loop="loop"> </audio>
Le format MP3 n’est pas supporté par votre navigateur. <figcaption>Tout le multimédia de HTML5</figcaption>
131 </audio> 132 </figure>
Programmation Web http://eric.univ-lyon2.fr/jdarmont/ Programmation Web http://eric.univ-lyon2.fr/jdarmont/
Programmation web

131 132

22
Jauges Listes ordonnées et non-ordonnées

 Barre de progression  Listes à puces : <ul> </ul>


<progress max="100" value="75"></progress>
 Listes numérotées : <ol> </ol>
Apparence :
 Exemple
 Barre de mesure <ul>
<meter min="0" max="100" low="10" high="90" <li>1er élément</li>
optimum="50" value="75">75 %</meter> <li>2ème élément</li>
Apparence : variable selon les navigateurs <li>3ème élément</li>
</ul>
133 Programmation Web Programmation web 134 Programmation web http://eric.univ-lyon2.fr/jdarmont/

133 134

Listes de définitions Imbrication de listes

 Exemple  Exemple
<dl>
<dt>1er terme</dt>
<dd>Définition du 1er terme</dd> <ul>
<dt>2ème terme</dt> <li>Elément non ordonné 1
<dd>Définition du 2ème terme</dd> <ol>
</dl> <li>Sous-élément ordonné 1.1</li>
<li>Sous-élément ordonné 1.2</li>
</ol>
 Résultat à l'affichage </li>
1er terme <li>Elément non ordonné 2</li>
Définition du 1er terme </ul>
2ème terme
Définition du 2ème terme
135 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 136 Programmation web http://eric.univ-lyon2.fr/jdarmont/

135 136

Tableaux simples Exemple de tableau

 Tableau : Ensemble de lignes elles-mêmes constituées <table>


de cellules <caption>Mes totaux</caption>
<tr>
 Définition d'un tableau : <table> </table> <th>Jour de la semaine</th> <th>Montant</th> <th>Total</th>
</tr>
 Légende : <caption> </caption> <tr>
<td>Lundi</td> <td>456 euros</td> <td>456 euros</td>
 Définition d'une ligne : <tr> </tr> </tr>
<tr>
 Définition d'une cellule d'en-tête : <th> </th> <td>Mardi</td> <td>200 euros </td> <td>656 euros </td>
</tr>
 Définition d'une cellule normale : <td> </td> </table>
137 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 138 Programmation web http://eric.univ-lyon2.fr/jdarmont/

137 138

23
Apparence du tableau exemple Tableaux à cellules recouvrantes (1/2)

Mes totaux
C1 C2 L1
Jour de la semaine Montant Total
Lundi 456 euros 456 euros L12
Mardi 200 euros 656 euros
C12 L2

139 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 140 Programmation web http://eric.univ-lyon2.fr/jdarmont/

139 140

Tableaux à cellules recouvrantes (2/2) Accessibilité (1/2)

 "Fusion" de cellules (<td> ou <th>) 26,4 % de la population française souffre d'une entrave
dans une activité quotidienne et 10 % est affectée d'un
 Cellule sur plusieurs colonnes : attribut colspan handicap. (SVM, novembre 2008)
– Ex. <table> <tr> <td>C1</td> <td>C2</td> </tr>
<tr> <td colspan="2">C12</td> </tr> </table> Préceptes d’accessibilité :

 Proposer un texte alternatif aux images et aux


 Cellule sur plusieurs lignes : attribut rowspan contenus multimédias en général (description,
– Ex. <table> <tr> <td rowspan="2">L12</td>
transcription…)
<td>L1</td> </tr>
<tr> <td>L2</td> </tr> </table>
 Utiliser des feuilles de style
141 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 142 Programmation web http://eric.univ-lyon2.fr/jdarmont/

141 142

Accessibilité (2/2) Plan du cours

 Prévoir des en-têtes de ligne et de colonnes dans les


tableaux  Objectifs du cours
 Lier chaque champ de formulaire à une légende  Bases de PHP
 Définir des raccourcis clavier  PHP objet
 Prévoir une alternative HTML aux technologies  Interface PHP-bases de données
propriétaires (ex. Flash)  Architecture MVC et gabarits
 Éviter l’usage des cadres (frames)  Annexes
Langage HTML5
 Prévenir des changements de langue dans le texte 
– Feuilles de style CSS3
 Expliciter les liens (« page d’accueil » >> « cliquer ici »)
143 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 144 Programmation web http://eric.univ-lyon2.fr/jdarmont/

143 144

24
Définition et caractéristiques Avantages

 Cascading Style Sheets (CSS) :  Gestion simplifiée et globale de la présentation d'un site
Feuilles de style en cascade
 Coûts de développement et de maintenance allégés
 Première spécification par le W3C en 1996 (code plus simple)
 Séparation du contenu et de la présentation
 Code source allégé
 Définition de styles génériques pour les éléments
 Possibilité de présentations différentes selon le profil
 Syntaxe différente de HTML utilisateur, la résolution écran…
 Possibilité de validation automatique  Meilleure accessibilité
145 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 146 Programmation web http://eric.univ-lyon2.fr/jdarmont/

145 146

Définitions de styles Notion de cascade

 Trois localisations possibles (+local au +global)  Imbrication des définitions : la plus locale l'emporte.
– Ex. Définition de style dans un fichier externe vs. définition
 Dans un élément HTML : attribut style
dans un élément
– Ex. <p style="color: blue; text-align: center;">…</p>  la définition locale de l’élément prévaut

 Dans une page HTML : élément <style>


– Dans l'en-tête de la page Web (head) :  Imbrication des éléments : le style d'un élément
<style type="text/css">…</style> s'applique aux éléments imbriquées.
– Ex. <p>…<em>…</em>…</p>
 Dans un fichier séparé Si un style est appliqué à <p>, il s'applique à <em>.
– Appel dans l'en-tête de la page Web (head) :
<link rel="stylesheet" type="text/css" href="feuille_style.css" />
147 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 148 Programmation web http://eric.univ-lyon2.fr/jdarmont/

147 148

Unités de taille Spécification de couleurs

 Nom prédéfini : aqua, black, blue, fucshia, green, gray,


 Unités absolues lime, maroon, navy, olive, purple, red, silver, teal,
– px : pixel white, yellow
– pt : point
 Spécification RGB (Rouge Vert Bleu - RVB)
 Unités relatives (à privilégier, cf. Responsive design) – Ex. Jaune : rgb(255, 255, 0)
– em : hauteur de ligne
– % : proportion par rapport à la taille de la fenêtre  Code RGB hexadécimal
– Ex. Jaune : #FFFF00

149 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 150 Programmation web http://eric.univ-lyon2.fr/jdarmont/

149 150

25
Écriture d'une feuille de style Sélecteurs

 Sélecteur universel : tous les éléments HTML


 Feuille de style : ensemble de règles
– Ex. * { color: blue; }
– Un sélecteur
– Des propriétés  Style d'une catégorie d’éléments
– Une valeur pour chaque propriété – Ex. h1 { color: #FF00FF; }

 Style de plusieurs catégories d’éléments


 Exemple
– Ex. h1, h2, h3, p { color: green; }
h1 {
color: yellow;
font-weight: bold;
 Style pour éléments imbriqués
} – Ex. p em { color: red; } /* Italiques dans un paragraphe */
(Commentaire)
151 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 152 Programmation web http://eric.univ-lyon2.fr/jdarmont/

151 152

Classe de style (1/2) Classe de style (2/2)

 Utilisation dans une page Web


 Sélecteur défini par l'utilisateur qui permet de dissocier – Ex. <h1 class="style_rouge">Titre rouge</h1>
un style d’éléments particuliers <p class="style_rouge">Texte rouge</p>
<p class="style_bleu">Texte bleu</p>
– Ex. .style_rouge { color: red; } <p class="parag_vert">Texte vert</p>
.style_bleu { color: blue; }
p.parag_vert { color: green; }
 Application à un ensemble d'éléments : <div> </div>
 Sélecteur associé à un identifiant particulier – Ex. <div class="style_bleu">
<h1>…</h1>
– Ex. #titre { text-align:center; color: navy; } <p>…</p>
<p>…</p>
</div>
153 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 154 Programmation web http://eric.univ-lyon2.fr/jdarmont/

153 154

Application des styles Propriétés de couleur

 À une partie d'un paragraphe : <span> </span>  color color: black;


color: #000000;
– Ex. <p class="style_rouge">Ceci est rouge sauf
<span class="style_bleu">ce qui est bleu</span>  background-color background-color: white;
</p> background-color: #FFFFFF;

 background-image background-image: url("URL");


 À un élément identifié :
– Ex. <div id="titre"> … </div>  background-repeat background-repeat: no-repeat;
<p id="titre"> … </p>
 background-position background-position: center;

155 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 156 Programmation web http://eric.univ-lyon2.fr/jdarmont/

155 156

26
Propriétés de typographie Propriétés de texte

 font-family font-family: times;


font-family: arial, verdana;  text-align text-align: left;
text-align: right;
 font-size font-size: 1.5em; text-align: center;
text-align: justify;
 font-style font-style: italic;
 text-indent text-indent: 10pt;
 font-weight font-weight: bold; text-indent: 15px;
font-weight: bolder; text-indent: 5%;

 text-decoration text-decoration: underline;


text-decoration: line-through;
157 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 158 Programmation web http://eric.univ-lyon2.fr/jdarmont/

157 158

Propriétés de boîte englobante (1/2) Propriétés de boîte englobante (2/2)


Boîte  width width: 80pt;
Page Web
margin-left
 height height: 25%;
width
Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla
padding-top
 padding padding: 5px;
bla bla bla bla bla bla bla bla bla bla bla
Tatabla blatata
tata bla bla
tatabla bla
tata -left, -right, -top, -bottom padding-bottom: 10px;
bla bla bla bla bla bla bla bla bla bla bla bla bla
tata tata tatablatata
bla bla
tatabla Boîte
bla bla bla bla bla bla bla bla bla bla bla
 margin margin: 10px;
tatabla blatata
tata blatata
bla bla
tatabla height centrée
bla bla bla bla bla bla bla bla bla bla bla -left, -right, -top, -bottom margin-left: 10%;
tatabla blatata
tata blatata
bla bla
tatabla
bla bla bla bla bla bla bla bla bla bla bla
tata tata tata tata… bla
bla bla bla bla bla margin-left: auto; margin-right: auto;
bla bla bla bla bla bla bla bla bla blapadding-left
bla bla bla bla bla bla bla  border border: 2px solid #FF00FF;
bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla
-width, -style, -color border-style: dotted; Coins
bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla
margin-bottom
bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla border-radius: 15px; ronds
bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla…  overflow overflow: auto;
159 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 160 Programmation web http://eric.univ-lyon2.fr/jdarmont/

159 160

Propriétés d'hyperlien Propriétés de liste

 Hyperliens
 Listes non-ordonnées
– Ex. a { color: blue; }
– list-style list-style: disc;
 Hyperliens visités list-style: circle;
list-style: square;
– Ex. a:visited { color: purple; }
– list-style-image list-style-image: url("URL");
 Hyperliens survolés (avec le pointeur de souris)
– Ex. a:hover { color: white; background-color: blue; }  Listes ordonnées
– list-style list-style: decimal;
 Hyperliens activés list-style: upper-roman;
– Ex. a:active { color: purple; } list-style: lower-alpha;

161 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 162 Programmation web http://eric.univ-lyon2.fr/jdarmont/

161 162

27
Propriétés de tableau Positionnement flottant (1/4)

 Élément table : border, width, Exemple 1 : menu flottant à droite Menu


border-collapse: collapse…
 Élément caption : caption-side: top;
caption-side: bottom;
(style
 Élément tr : height .menu_jaune)

 Éléments td et th : border, width… 100 pixels


vertical-align: top;
vertical-align: middle;
vertical-align: bottom;
163 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 164 Programmation web http://eric.univ-lyon2.fr/jdarmont/

163 164

Positionnement flottant (2/4) Positionnement flottant (3/4) Conteneur


(style .page)
100 %
 Exemple 1 : Exemple 2 : pagination en trois colonnes

 CSS .menu_jaune { float: right;


background-color: yellow;
width: 100px; }
Colonne 1 Colonne 2 Colonne 3
 HTML <div class="menu_jaune">
<p>Menu</p> (style .colonne) (style .colonne) (style .colonne)
</div> 33 % 33 % 33 %
<div>
<!-- Contenu de la page -->
</div>

165 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 166 Programmation web http://eric.univ-lyon2.fr/jdarmont/

165 166

Positionnement flottant (4/4) Positionnement absolu (1/2)


1em
 Exemple 2 :
Bla bla sur fond vert… 1em
Idem sur fond jaune
Bla bla sur fond vert…
 CSS .page { float: left; width: 100%; } Bla bla sur fond vert…
.colonne { float: left; width: 33%; }
15em

 HTML <div class="page"> <!-- Conteneur -->  HTML <div class="boite_verte">


<div class="colonne"> </div> <p>Bla bla sur fond vert…</p>
<div class="colonne"> </div> <div class="boite_jaune">
<div class="colonne"> </div> <p>Idem sur fond jaune</p>
</div> </div>
</div>
167 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 168 Programmation web http://eric.univ-lyon2.fr/jdarmont/

167 168

28
Positionnement absolu (2/2) Exemple de mise en page : Objectif

 CSS .boite_verte { position: relative;


background-color: #00FF00;
width: 15em; }

.boite_jaune { position: absolute;


top: 1em;
right: 1em;
background-color: #FFFF00; }

169 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 170 Programmation web http://eric.univ-lyon2.fr/jdarmont/

169 170

Exemple de mise en page : HTML Exemple de mise en page : CSS

<main> *{ nav {
font-family: arial; float: left;
<header> width: 200px;
}
<h1>Exemple de mise en page</h1> body { background-color: red;
</header> background-color: silver; padding: 1em;
} border-radius: 15px;
<div id="conteneur">
main { }
<nav> section {
width: 1000px;
<a href="http://www.univ-lyon2.fr">Université Lyon 2</a> margin-left: auto; float: left;
</nav> margin-right: auto; width: 750px;
background-color: white; background-color: lime;
<section>
padding: 1em; margin-left: 1em;
<article>Article 1</article> border-radius: 15px;
}
<article>Article 2</article> header { }
<article>Article 3</article> background-color: yellow; article {
text-align: center; background-color: aqua;
</section>
padding: 1em; margin: 1em;
</div> }
border-radius: 15px;
<footer> } footer {
&copy; IDS #conteneur { background-color: fuchsia;
width: 100%; text-align: center;
</footer>
margin-top: 1em; padding: 1em;
</main> border-radius: 15px;
171 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 172 }
Programmation web } http://eric.univ-lyon2.fr/jdarmont/

171 172

Responsive design Responsive design en pratique (1/2)

 Grilles fluides : utilisation des unités relatives

http://blog.teamtreehouse.com/modern-field-guide-responsive-web-design

blog.teamtreehouse.com
– Sidebar : 300px / 960px = 31.25%
– Main Content : 640px / 960px = 66.67%
– Margin : 20px / 960px = 2.08%
173 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 174 Programmation web http://eric.univ-lyon2.fr/jdarmont/

173 174

29
Responsive design en pratique (2/2) Grilles (1/3) https://blog.goetter.fr/2016/01/02/grid-layout-vers-la-grille-parfaite/

 Images fluides
 Remplacent les mises en forme classiques
– Taille variable en fonction de la grille fluide
– CSS
img { max-width: 100%; }  Définition d’une grille

 Requêtes de média .conteneur {


display: grid; /* conteneur grille */
– Application de style conditionnelle grid-template-columns: repeat(4, 1fr); /* 4 cols, même taille */
– CSS grid-gap: 1rem; /* gouttière verticale et horizontale */
@media screen and (min-width: 300px) { /* styles pour mobiles */ } }
@media screen and (min-width: 600px) { /* styles pour tablettes */ }
@media screen and (min-width: 900px) { /* styles pour ordis */ }
175 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 176 Programmation web http://eric.univ-lyon2.fr/jdarmont/

175 176

Grilles (2/3) Grilles (3/3)

 Grille adaptative
 Éléments à taille multiple /* Tablette : 2 colonnes */
@media (max-width: 640px) {
@media (min-width: 481px) { .container {
.col-span { grid-template-columns: repeat(2, 1fr);
grid-column: span 2; /* double taille en largeur */ }
} }
.row-span { /* Téléphone mobile : 1 colonne */
grid-row: span 2 /* double taille en hauteur */ @media (max-width: 480px) {
} .container {
} grid-template-columns: 1fr;
}
}
177 Programmation web http://eric.univ-lyon2.fr/jdarmont/ 178 Programmation web http://eric.univ-lyon2.fr/jdarmont/

177 178

Plan du cours

 Objectifs du cours
 Bases de PHP
 PHP objet
 Interface PHP-bases de données
 Architecture MVC et gabarits
 Annexes
 Langage HTML5
 Feuilles de style CSS3

179 Programmation web http://eric.univ-lyon2.fr/jdarmont/

179

30

Vous aimerez peut-être aussi