PHP — The basics

Guide 02 / 4

PHP essentials

An annotated cheat sheet: what each element is for, how to write it and when to use it.

Expected outcome :

Choose and use the essential elements to complete this step of the blog.

Reading
0%

01 · Writing the essential processing

Revisit the programming concepts with PHP syntax.

PHP tags, echo and interpolation

The server runs the code between <?php and ?>. echo writes into the response; <?= … ?> is its shortcut in an HTML template.

<?php $titre = "Soupe"; ?>
<h1><?= htmlspecialchars($titre, ENT_QUOTES, "UTF-8") ?></h1>
Remember :

In a file that is purely PHP, omitting ?> avoids accidental output whitespace.

Concatenation and strict comparison

The dot joins strings. === compares type and value; !== is notably used to tell false apart from a position 0.

echo "Durée : " . 20 . " minutes";
var_dump(0 !== false); // true

if, foreach and template syntax

if chooses a branch. foreach goes through the recipes. In HTML, : and endforeach make blocks easier to spot.

<?php foreach ($recettes as $recette): ?>
  <h2><?= h($recette["titre"]) ?></h2>
<?php endforeach; ?>
Remember :

This excerpt assumes the h function defined in includes/functions.php.

require, return and __DIR__

require loads a necessary file and stops the script if it is missing. __DIR__ gives the current file's directory. A data file can return an array with return.

$recettes = require __DIR__ . '/../includes/recettes.php';
Remember :

From public/index.php, ../ goes up to mini-blog/. No file path should come directly from user input.

array_filter and use

array_filter keeps the elements for which the function returns true. use makes an outer variable available inside an anonymous function.

$recettes = array_filter($recettes, function (array $recette) use ($q): bool {
    return mb_stripos($recette['titre'], $q, 0, 'UTF-8') !== false;
});
Remember :

mb_stripos can return 0 if the word is at the start: compare strictly with false.

02 · Checking inputs and displaying outputs

HTML controls help the user; the server enforces the rules.

??, is_string and trim

?? provides a default value if a key is missing or null. is_string rejects unexpected forms such as titre[]. trim removes spaces at the ends.

$valeur = $_POST['titre'] ?? '';
$titre = is_string($valeur) ? trim($valeur) : '';
Remember :

The texte function in the complete examples groups these operations.

filter_var and a bounded integer

FILTER_VALIDATE_INT checks that a piece of data represents an integer. The bounds express the business rule; false indicates failure.

$duree = filter_var('20', FILTER_VALIDATE_INT, [
    'options' => ['min_range' => 1, 'max_range' => 1440],
]);
if ($duree === false) { echo 'Durée invalide'; }

mb_strlen for the title length

mb_strlen counts the characters of a UTF-8 string rather than bytes. The workshop accepts between 3 and 120 characters.

if (mb_strlen($titre, 'UTF-8') < 3 || mb_strlen($titre, 'UTF-8') > 120) {
    $erreurs[] = 'Le titre doit contenir entre 3 et 120 caractères.';
}
Remember :

The mbstring extension is required. An accent can take several bytes without being several characters.

htmlspecialchars and the h function

The h function centralises escaping for HTML text and quoted HTML attribute contexts. The raw text is kept in the data.

function h(string $valeur): string
{
    return htmlspecialchars($valeur, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
Remember :

This function is not a universal escape for JavaScript, CSS or an arbitrary URL.

explode and HTML lists

explode splits a string on a delimiter. Ingredients and steps use one line per item to keep a simple model that is compatible with future SQL.

<?php foreach (explode("\n", $recette["ingredients"]) as $ligne): ?>
  <li><?= h($ligne) ?></li>
<?php endforeach; ?>

Local working commands

Run from mini-blog/. -l checks a file's syntax; -S starts a development server; -t limits its public root.

php -v
php -m
php -l public/index.php
php -S 127.0.0.1:8000 -t public
Remember :

Open http://127.0.0.1:8000/index.php. The built-in server is for local development.