Development and production

Course Beginner Free

PHP — The basics

Generate pages from server-side data and handle a form securely.

  • 4 guides
  • 37 concepts
Start reading

Guides

  1. 01 Guide PHP glossary Explain the concepts in your own words and recognise them in an example. 12 concepts
  2. 02 Guide PHP essentials Choose and use the essential elements to complete this step of the blog. 11 concepts
  3. 03 Guide PHP workshop · À table ! Reproduce a working result, test it, then succeed at an exercise without copying. 8 concepts
  4. 04 Guide Resources and review Find reliable information and explain what you have built. 6 concepts

Suggested path

  1. 01. HTML: structure three recipes in a semantic page.
  2. 02. CSS: make the blog readable on mobile and on desktop.
  3. 03. JavaScript: filter the recipes without reloading the page.
  4. 04. PHP: produce the pages from arrays and process a form.
  5. 05. MySQL: keep the recipes in a relational database.
  6. 06. PDO: read and add recipes from PHP with prepared queries.

Sources and references

Beginner workshop, step 4/6. The complete files are materials to reproduce in a separate local project. Read the prerequisites, the expected results and the limits stated in the workshop.

Example files

includes/functions.php
<?php
// Fichier PHP sans balise de fermeture pour éviter les sorties accidentelles.
function h(string $valeur): string
{
    return htmlspecialchars($valeur, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function texte(array $donnees, string $cle): string
{
    $valeur = $donnees[$cle] ?? '';
    return is_string($valeur) ? trim($valeur) : '';
}
includes/recettes.php
<?php
return [
    [
        'id' => 1, 'titre' => 'Soupe de carottes', 'duree_minutes' => 20,
        'portions' => 2, 'categorie' => 'Plat',
        'ingredients' => "4 carottes\n1 oignon\n500 ml d’eau",
        'etapes' => "Éplucher et couper les légumes.\nCuire dans l’eau 15 minutes puis mixer.",
    ],
    [
        'id' => 2, 'titre' => 'Salade de tomates', 'duree_minutes' => 10,
        'portions' => 2, 'categorie' => 'Entrée',
        'ingredients' => "3 tomates\n1 cuillère d’huile d’olive\nQuelques feuilles de basilic",
        'etapes' => "Laver et couper les tomates.\nAjouter l’huile et le basilic, mélanger.",
    ],
    [
        'id' => 3, 'titre' => 'Tarte aux pommes', 'duree_minutes' => 45,
        'portions' => 4, 'categorie' => 'Dessert',
        'ingredients' => "1 pâte brisée\n3 pommes\n2 cuillères de compote",
        'etapes' => "Préchauffer le four à 180 °C et étaler la pâte.\nGarnir de compote et de pommes puis cuire 30 minutes.",
    ],
];
public/index.php
<?php
require __DIR__ . '/../includes/functions.php';
$recettes = require __DIR__ . '/../includes/recettes.php';
$q = texte($_GET, 'q');
if ($q !== '') {
    $recettes = array_filter($recettes, function (array $recette) use ($q): bool {
        return mb_stripos($recette['titre'], $q, 0, 'UTF-8') !== false;
    });
}
?>
<!doctype html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>À table ! · Recettes PHP</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <header class="entete"><h1>À table !</h1><a href="proposer.php">Proposer une recette</a></header>
  <main class="conteneur">
    <h2>Nos recettes maison</h2>
    <form method="get" action="index.php">
      <label for="q">Rechercher par titre</label>
      <input id="q" type="search" name="q" value="<?= h($q) ?>">
      <button type="submit">Rechercher</button>
      <a href="index.php">Tout afficher</a>
    </form>
    <p><?= count($recettes) ?> recette(s) trouvée(s).</p>
    <?php if ($recettes === []): ?><p>Aucune recette trouvée.</p><?php endif; ?>
    <div class="recettes">
      <?php foreach ($recettes as $recette): ?>
        <article class="recette">
          <h3><a href="recette.php?id=<?= $recette['id'] ?>"><?= h($recette['titre']) ?></a></h3>
          <p class="meta"><?= $recette['duree_minutes'] ?> min · <?= $recette['portions'] ?> personnes · <?= h($recette['categorie']) ?></p>
        </article>
      <?php endforeach; ?>
    </div>
  </main>
</body>
</html>
public/recette.php
<?php
require __DIR__ . '/../includes/functions.php';
$recettes = require __DIR__ . '/../includes/recettes.php';
$id = filter_var($_GET['id'] ?? null, FILTER_VALIDATE_INT, [
    'options' => ['min_range' => 1],
]);
if ($id === false) {
    http_response_code(400);
    exit('Identifiant de recette invalide.');
}
$recette = null;
foreach ($recettes as $candidate) {
    if ($candidate['id'] === $id) {
        $recette = $candidate;
        break;
    }
}
if ($recette === null) {
    http_response_code(404);
    exit('Recette introuvable.');
}
?>
<!doctype html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?= h($recette['titre']) ?> · À table !</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <main class="conteneur">
    <a href="index.php">Toutes les recettes</a>
    <article class="recette">
      <h1><?= h($recette['titre']) ?></h1>
      <p><?= $recette['duree_minutes'] ?> min · <?= $recette['portions'] ?> personnes · <?= h($recette['categorie']) ?></p>
      <h2>Ingrédients</h2>
      <ul><?php foreach (explode("\n", $recette['ingredients']) as $ligne): ?>
        <li><?= h($ligne) ?></li>
      <?php endforeach; ?></ul>
      <h2>Préparation</h2>
      <ol><?php foreach (explode("\n", $recette['etapes']) as $ligne): ?>
        <li><?= h($ligne) ?></li>
      <?php endforeach; ?></ol>
    </article>
  </main>
</body>
</html>
public/proposer.php
<?php
require __DIR__ . '/../includes/functions.php';
$erreurs = [];
$titre = '';
$dureeSaisie = '';
$valide = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $titre = texte($_POST, 'titre');
    $dureeSaisie = texte($_POST, 'duree_minutes');
    $duree = filter_var($dureeSaisie, FILTER_VALIDATE_INT, [
        'options' => ['min_range' => 1, 'max_range' => 1440],
    ]);
    if (mb_strlen($titre, 'UTF-8') < 3 || mb_strlen($titre, 'UTF-8') > 120) {
        $erreurs[] = 'Le titre doit contenir entre 3 et 120 caractères.';
    }
    if ($duree === false) {
        $erreurs[] = 'La durée doit être un entier entre 1 et 1440 minutes.';
    }
    $valide = $erreurs === [];
}
?>
<!doctype html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Proposer une recette · À table !</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <main class="conteneur">
    <a href="index.php">Toutes les recettes</a>
    <h1>Proposer une recette</h1>
    <p>Exercice : les données sont vérifiées mais ne sont pas enregistrées.</p>
    <?php if ($erreurs !== []): ?>
      <div role="alert"><ul><?php foreach ($erreurs as $erreur): ?>
        <li><?= h($erreur) ?></li>
      <?php endforeach; ?></ul></div>
    <?php endif; ?>
    <?php if ($valide): ?>
      <p role="status">« <?= h($titre) ?> » : proposition valide, <?= $duree ?> minutes. Aucun enregistrement effectué.</p>
    <?php endif; ?>
    <form method="post" action="proposer.php">
      <p><label for="titre">Titre</label><br>
        <input id="titre" name="titre" required minlength="3" maxlength="120" value="<?= h($titre) ?>"></p>
      <p><label for="duree_minutes">Durée en minutes</label><br>
        <input id="duree_minutes" name="duree_minutes" type="number" required min="1" max="1440" value="<?= h($dureeSaisie) ?>"></p>
      <button type="submit">Vérifier la proposition</button>
    </form>
  </main>
</body>
</html>

In the same series Step 4 of 6

  1. 1 Course HTML — The basics
  2. 2 Course CSS — The basics
  3. 3 Course JavaScript — The basics
  4. 4 Course PHP — The basics You are here
  5. 5 Course MySQL — The basics
  6. 6 Course PDO — The basics

Share this article

In the same category

Course

Development and production · Beginner

HTML — The basics

Build a semantic, accessible web page step by step with a running project: a recipe mini-blog.

4 guides · 38 concepts In the same series

Course

Development and production · Intermediate

Node.js — The fundamentals

Understand the Node.js runtime: modules, asynchronous code, npm and building a small server.

4 guides · 44 concepts In the same series

Course

Development and production · Beginner

CSS — The basics

Style the recipe mini-blog and make it responsive: selectors, box model, flexbox, grid and mobile-first.

4 guides · 39 concepts In the same series