Skip to content

Instantly share code, notes, and snippets.

@Godefroy
Last active November 7, 2020 21:49
Show Gist options
  • Save Godefroy/e22bfc82b5f29d6c55879e230fa62e0e to your computer and use it in GitHub Desktop.
Save Godefroy/e22bfc82b5f29d6c55879e230fa62e0e to your computer and use it in GitHub Desktop.
TP PHP Procédural - Site basique avec interface admin
<?php
include 'check_auth.php';
$username = $_SESSION['username'];
// Cookie "visits"
if (isset($_COOKIE['visits']) && ctype_digit($_COOKIE['visits'])) {
$visits = $_COOKIE['visits'] + 1;
} else {
$visits = 1;
}
$expiration = time() + 30 * 24 * 3600; // Dans 1 mois
// Envoi du cookie au navigateur
setcookie('visits', $visits, $expiration);
?>
<html>
<body>
<p>
Bienvenue <?php echo htmlspecialchars($username); ?> !
</p>
<p>
C'est la <?php echo $visits; ?>ème fois que tu viens :-)
</p>
<?php
include 'admin_links.php';
?>
</body>
</html>
<?php
include 'check_auth.php';
// Enregistrement du contenu
if (isset($_POST['content'])) {
file_put_contents('home.txt', $_POST['content']);
}
// Récupération du contenu à afficher
$content = file_get_contents('home.txt');
// Enregistrement de l'image
$upload_errors = [];
if (isset($_FILES['image'])) {
$file = $_FILES['image'];
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
// Taille max: 1 Mo
if ($file['size'] > 1024 * 1024) {
$upload_errors[] = 'MAX_SIZE';
}
// Extension autorisée: jpg
if ($extension != 'jpg') {
$upload_errors[] = 'EXTENSION';
}
if (count($upload_errors) == 0) {
// On essaie de déplacer le fichier à l'endroit voulu
$success = move_uploaded_file($file['tmp_name'], 'home.jpg');
if (!$success) {
$upload_errors[] = 'ERROR';
}
}
}
// Suppression de l'image
if (isset($_POST['delete']) && file_exists('home.jpg')) {
unlink('home.jpg');
}
?>
<html>
<body>
<?php
include 'admin_links.php';
?>
<form action="?" method="post" enctype="multipart/form-data">
<p>
<label>
Texte :<br/>
<textarea name="content" cols="50" rows="10"><?php echo htmlspecialchars($content); ?></textarea>
</label>
</p>
<p>
<label>
Image (Extension .jpg, Max 1 Mo) :<br/>
<input type="file" name="image"/>
</label>
<?php
if (count($upload_errors) != 0) {
echo '<ul>';
foreach ($upload_errors as $error) {
switch ($error) {
case 'MAX_SIZE':
$error_message = 'Le fichier ne doit pas dépasser 1 Mo';
break;
case 'EXTENSION':
$error_message = 'Le fichier doit avoir l\'extension jpg';
break;
default:
$error_message = 'Une erreur s\'est produite :-(';
}
echo '<li style="color: red; font-weight: bold;">' . $error_message . '</li>';
}
echo '</ul>';
}
?>
</p>
<?php if (file_exists('home.jpg')){ ?>
<div style="border: 2px solid #666; padding: 15px; width: 100px;">
<p>
<img src="home.jpg" width="100" height="100"/>
</p>
<p>
<input type="submit" name="delete" value="Supprimer"/>
</p>
</div>
<?php } else { ?>
<p>
(Pas d'image pour le moment)
</p>
<?php } ?>
<p>
<input type="submit" value="Enregister"/>
</p>
</form>
</body>
</html>
<?php
session_start();
// Session inexistante
if (!isset($_SESSION['username'])) {
header('Location: login.php');
exit;
}
<?php
// Récupération du contenu à afficher
if (file_exists('home.txt')) {
$content = file_get_contents('home.txt');
$content = htmlspecialchars($content);
// Markdown (subset)
// Titres
$content = preg_replace('~^#([^#]+)$~m', '<h1>$1</h1>', $content);
$content = preg_replace('~^##([^#]+)$~m', '<h2>$1</h2>', $content);
$content = preg_replace('~^###([^#]+)$~m', '<h3>$1</h3>', $content);
// Italique & Gras
$content = preg_replace('~\*\*([^*]+)\*\*~', '<strong>$1</strong>', $content);
$content = preg_replace('~\*([^*]+)\*~', '<em>$1</em>', $content);
// Listes
$content = preg_replace('~^-(.+)$~m', '<li>$1</li>', $content);
$content = preg_replace('~(?<!</li>\n)<li>~', "<ul>\n<li>", $content);
$content = preg_replace('~</li>(?!\n<li>)~', "</li>\n</ul>", $content);
} else {
$content = '';
}
?>
<html>
<head>
<title>Page d'accueil</title>
</head>
<body>
<p>
<?php if (file_exists('home.jpg')): ?>
<img src="home.jpg" width="200"/>
<?php endif; ?>
</p>
<p>
<?php echo $content; ?>
</p>
</body>
</html>
<?php
session_start();
/*
// Génération d'un hash de mot de passe
echo password_hash('example', PASSWORD_DEFAULT);
exit;
*/
$users = [
'Bob' => '$2y$10$iA1IhMpUrnv.ghkjJTgWIeT8i/0fs8xIGzJQyXMf.7Ur3x34V8p4C',
'Alice' => '$2y$10$uJsVwBFjC63W/1UVESPWPuAuPxcozw6r1LYhp/.ombPlvca6IlkJa'
];
$error = false;
// Envoi du formulaire
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// Vérification des identifiants
if (isset($users[$username]) && password_verify($password, $users[$username])) {
$_SESSION['username'] = $username;
} else {
// Erreur car $username non trouvé dans $users ou mot de passe incorrect
$error = true;
}
} else {
// Pas d'envoi du formulaire
$username = '';
}
// Déconnexion
if (isset($_GET['logout'])) {
session_destroy();
//unset($_SESSION['username']);
}
// Redirection vers admin.php si la session existe
if (isset($_SESSION['username'])) {
header('Location: admin.php');
exit;
}
?>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<form action="?" method="post">
<p>
<label>
Nom d'utilisateur :
<input type="text" name="username" value="<?php echo htmlspecialchars($username); ?>"/>
</label>
</p>
<p>
<label>
Mot de passe :
<input type="password" name="password"/>
</label>
</p>
<?php if ($error): ?>
<p style="font-weight: bold; color: red;">
Nom d'utilisateur ou mot de passe incorrect
</p>
<?php endif; ?>
<p>
<input type="submit" value="Connecter" class="btn btn-primary"/>
</p>
</form>
</div>
</div>
</div>
</body>
</html>
<pre>
<?php
// Test de calcul de moyennes et tri
// Liste des notes pour chaque étudiant
$students = [
'Alice' => [11, 12, 9, 18],
'Bob' => [12.5, 15, 8, 13],
'John' => [18, 13, 14, 6]
];
// Calcul des moyennes
$avg_notes = [];
foreach ($students as $firstname => $notes) {
// Moyenne = Somme des notes / Nombre de notes
$avg_notes[$firstname] = array_sum($notes) / count($notes);
}
// Tri des étudiants par leur moyenne
arsort($avg_notes);
// Affichage
foreach ($avg_notes as $firstname => $note) {
echo $firstname . ': ' . round($note, 1) . "\n";
}
?>
</pre>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment