Build a website in PHP. This first project was to show you the basics of building a website using PHP now we are modifying it to support external data so that the content and the function are totally seperate.
<? // contents of index.php
require DIR . ‘/dplwebsite.php’; // include our class definition
// beginning of php code
// set up data in array
$pages = array();
// create data array for home page
$page = array();
$page[‘name’]=’home’;
$page[‘title’]=’Home’;
$page[‘link’]=’Home‘;
$page[‘heading’]=’Home page’;
$page[‘content’]=”Welcome to my new website.”;
$pages[]=$page; // add home page to array
// create data array for about page
$page = array();
$page[‘name’]=’about’;
$page[‘title’]=’About’;
$page[‘link’]=’About‘;
$page[‘heading’]=”About Me”;
$page[‘content’]=”I’ve been working with websites for over twenty years.”;
$pages[]=$page; // add home page to array
// create data array for contact page
$page = array();
$page[‘name’]=’contact’;
$page[‘title’]=’Contact’;
$page[‘link’]=’Contact‘;
$page[‘heading’]=’Contact Me’;
$page[‘content’]=’Contact me using this link:
duetltd@gmail.com‘;
$pages[]=$page; // add home page to array
$website = new DplWebsite($pages);
$website->setdata();
$website->showdata();
<? // contents of dplwebsite.php
/**
* The Website creator
*
* @since 1.0.0 May 10, 2024
*
* @modified 1.0.1 June 7, 2024 Added external data for website content
*
* @package Dplwebsite
*
**/
Class DplWebsite { // create html website
private $page; // page to view
private $title; // page title
private $heading; // page heading
private $content; // page content
private $navbar; // navigation bar
private $mypages=array(); // set up data container
function __construct($pages){ // https://www.w3schools.com/php/php_oop_constructor.asp
$this->mypages=$pages;
}
public function setdata () { // set the local data based upon the page selected
$this->page=isset($_GET["page"]) ? $_GET["page"] : 'home';
$this->navbar=""; // start with empty navbar
$this->title='';
$this->heading='';
$this->content='';
foreach ($this->mypages as $mypage) {
$this->navbar.=$mypage['link'].' ';
if ($mypage['name']==$this->page){
$this->title=$mypage['title'];
$this->heading=$mypage['heading'];
$this->content=$mypage['content'];
}
if ($mypage['name']==$this->page){
$this->title=$mypage['title'];
$this->heading=$mypage['heading'];
$this->content=$mypage['content'];
}
if ($mypage['name']==$this->page){
$this->title=$mypage['title'];
$this->heading=$mypage['heading'];
$this->content=$mypage['content'];
}
}
}
public function showdata () { // show the website based upon the page selected
echo "<!DOCTYPE html>\n";
echo "<html>\n";
echo " <head>\n";
echo " <title>".$this->title."</title>\n";
echo " </head>\n";
echo " <body>\n";
echo " <h1>".$this->heading."</h1>\n";
echo " <p>".$this->navbar."</p>\n";
echo " <p>".$this->content."</p>\n";
echo " </body>\n";
echo "</html>\n";
}
}