CSCI 2006 - Spring 2024 - Server-Side ProgrammingLab #5 - PHP ClassesSolution

Solution

index.php

<?php

date_default_timezone_set('America/Chicago');
$date_string = date('Y-m-d H:i');

require('language.php');

$title = '404 Error';
$body = '<h2>404 Error</h2><p>The requested page was not available</p>';

if (!isset($_GET['pg'])) { 
	$title = 'Programming Languages';
	$_GET['pg'] = 'c'; 
}

$lang = new Language($_GET['pg']);
if ($lang->isDefined()) {
	$title = $lang->getName();
	$body = $lang->toHTML();
}

$allLangs = Language::getAllLanguages();
$nav = '';
foreach ($allLangs as $key=>$disp) {
	$nav .= '<a href="?pg='.$key.'" class="'.(($_GET['pg']==$key)?'currentPage':'').'">'.$disp.'</a>';
}

?>
<!DOCTYPE html>
<html>
<head>
  <title><?php echo $title; ?></title>
  <link rel="stylesheet" href="/style.css" type="text/css" media="all">
</head>
<body>
  <header>
    <h1>Programming Languages</h1>
    <nav><?php echo $nav; ?></nav>
  </header>
  <main>
  <?php echo $body; ?>
  </main>
  <script type="text/javascript" src="/theme/prism.js"></script>
  <footer>
    &copy;<?php echo $date_string; ?> - General Websites Inc.
  </footer>
</body>
</html>

language.php

<?php

require('/var/www/html/resources/csci2006data.php');

class Language {
	private $data = [];

	public function __construct($key) {
		$this->data = getCSCI2006Data('language',$key);
	}

	public function isDefined() {
		return ($this->data !== null); 
	}

	public function getName() {
		return $this->data['name'];
	}

	public function toHTML() {
		$html = '';
		foreach ($this->data['desc'] as $line) {
			$html .= '<p>'.$line.'</p>';
		}
		$html .= '<h2>Example</h2>'.
			'<pre class="language-'.$this->data['highlight'].' line-numbers"><code class="language-'.$this->data['highlight'].'">'.
			htmlentities($this->data['example']).
			'</code></pre>';
		return $html;
	}

	public static function getAllLanguages() {
		return getCSCI2006Data('language');
	}
}

?>
Go To Live Site