Challenge - Mini CMS
Build a simple content management page with include, arrays and a form.
Challenge - Mini CMS
In this challenge you'll build a simple mini CMS. You'll keep pages in a $pages associative array, list them with foreach and add a new page from $_POST form data.
In a real CMS page data is loaded from separate files with include; here we keep it in one file for simplicity. You check the key with isset and, if not empty, add the new page to the array.
Exercise Write the mini CMS page
Simulate form data with $_POST = ["title" => "Blog", "body" => "New posts"]. Add "home" => ["title" => "Home", "body" => "Welcome"] and "about" => ["title" => "About", "body" => "Who we are"] to the $pages associative array. Check with if (isset($_POST["title"]) && $_POST["title"] !== ""); when true add $pages["blog"] = ["title" => $_POST["title"], "body" => $_POST["body"]]. Finally loop with foreach ($pages as $slug => $page) and print echo $page["title"] . " /" . $slug . "\n".
Show example solution
Add home and about pages to the $pages associative array; read title and body from $_POST; check with isset, if !== "" add as $pages["blog"]; print title and slug with foreach.
Example solution:
<?php
// Mini CMS: page array and form to add a new page
$_POST = ["title" => "Blog", "body" => "New posts"];
$pages = [
"home" => ["title" => "Home", "body" => "Welcome"],
"about" => ["title" => "About", "body" => "Who we are"],
];
if (isset($_POST["title"]) && $_POST["title"] !== "") {
$pages["blog"] = ["title" => $_POST["title"], "body" => $_POST["body"]];
}
foreach ($pages as $slug => $page) {
echo $page["title"] . " /" . $slug . "\n";
}
Test yourself
-
What do you use to add a new page in the mini CMS?
- Load a file with include
- Read form data with $_POST
- Print to screen with echo
- Count with count
Show answer
Read form data with $_POST — Correct. Form data comes through the $_POST superglobal; you check its presence with isset.
-
Complete the foreach loop
foreach ($pages ____ $slug => $page) { echo $page["title"]; }Show answer
foreach ($pages as $slug => $page) { echo $page["title"]; } -
Match the CMS parts
- $pages
- page data
- foreach
- lists pages
- $_POST
- form data
- isset
- key check