Skip to main content
Course/Module 10/Topic 3 of 4Advanced

Views, Templates & File Uploads

Build a template system with PHP includes, implement file uploads for featured images, and create a responsive admin dashboard.

50 minBy Priygop TeamLast updated: Feb 2026

PHP Templating

  • Layout Template: views/layout.php — contains HTML boilerplate, <head>, navigation, footer. Content inserted via <?php include $contentView; ?>. Pass variables to views with extract($data)
  • Template Variables: function render(string $view, array $data = []) { extract($data); ob_start(); include 'views/' . $view . '.php'; return ob_get_clean(); } — output buffering captures HTML as string
  • Partials: include 'views/partials/header.php' for reusable components — navigation bar, sidebar, post card, pagination links. Each partial receives variables from parent scope
  • Post Card: <article class='post-card'><img src='<?= htmlspecialchars($post['image']) ?>' alt=''><h2><a href='/post/<?= $post['slug'] ?>'><?= htmlspecialchars($post['title']) ?></a></h2><p><?= htmlspecialchars($post['excerpt']) ?></p></article>
  • Pagination Links: Generate page links dynamically — for ($i = 1; $i <= $totalPages; $i++) { $active = $i === $currentPage ? 'active' : ''; echo '<a href="?page=' . $i . '" class="' . $active . '">' . $i . '</a>'; }
  • Flash Messages: $_SESSION['flash'] = ['type' => 'success', 'message' => 'Post created!']; — display once on next page load, then unset. Check and display in layout template

File Upload & Image Handling

  • Upload Form: <form method='POST' enctype='multipart/form-data'> — enctype is required for file uploads. <input type='file' name='featured_image' accept='image/*'> for client-side filtering
  • Server Validation: Check $_FILES['featured_image']['error'] === UPLOAD_ERR_OK, verify size < 5MB, validate MIME type with finfo_file($finfo, $_FILES['featured_image']['tmp_name'])
  • Secure Storage: $filename = uniqid('img_') . '.' . pathinfo($original, PATHINFO_EXTENSION); move_uploaded_file($_FILES['featured_image']['tmp_name'], 'uploads/' . $filename); — random filename prevents overwrites
  • Image Resizing: Use GD library — $image = imagecreatefromjpeg($path); $thumb = imagecreatetruecolor(300, 200); imagecopyresampled($thumb, $image, 0, 0, 0, 0, 300, 200, $origWidth, $origHeight); — create thumbnails
  • Rich Text Editor: Include TinyMCE or CKEditor via CDN — <textarea id='content' name='content'></textarea> <script>tinymce.init({selector: '#content'})</script>. Sanitize HTML output on display
  • Admin Dashboard: Protected page showing post count, recent posts table with edit/delete actions, user management (admin only). Use CSS Grid for dashboard layout with sidebar navigation
Chat on WhatsApp
Priygop - Leading Professional Development Platform | Expert Courses & Interview Prep