Create a flat file PHP blog script that reads markdown .md files from /posts, that uses Parsdown.php and highlight.js, has pagination and supports post truncation, and has a YAML parser
Assistant
Certainly! I'll help you create a flat-file PHP blog script that meets your requirements:
Reads Markdown .md files from /posts directory
Uses Parsedown.php for Markdown parsing
Integrates highlight.js for syntax highlighting
Supports pagination
Implements <!--readmore--> for post truncation
Parses YAML front matter for metadata
Overview
We'll build a simple PHP script that reads Markdown files from a posts directory, parses them with Parsedown.php, and displays them on a blog page with pagination. We'll use highlight.js for syntax highlighting in code blocks. Each Markdown file can contain YAML front matter for metadata like the title, date, and tags.
Steps
Set Up the Directory Structure
Include Required Libraries
Create Markdown Posts with YAML Front Matter
Implement the PHP Blog Script
Read and parse Markdown files
Parse YAML front matter
Implement pagination
Support <!--readmore--> for post truncation
Integrate highlight.js
Styling with CSS (Optional)
1. Set Up the Directory Structure
Create the following directory structure for your project:
Create your Markdown posts in the posts/ directory. Each post should have YAML front matter at the top, enclosed by ---.
Example: posts/post1.md
markdown
---
title: My First Blog Post
date: 2023-10-01
tags: php, markdown, blog
---
This is the content of my first blog post.
<!--readmore-->
The rest of the content that will be hidden on the blog index page.
4. Implement the PHP Blog Script
index.php
Here's the complete code with explanations:
php
<?php
// Include Parsedown and YAML parser
include_once 'includes/Parsedown.php';
include_once 'includes/YAMLParser.php';
$posts_dir = 'posts/';
$posts_per_page = 5;
// Get all Markdown files from the posts directory
$files = glob($posts_dir . '*.md');
// Sort files by modification time, newest first
usort($files, function($a, $b) {
return filemtime($b) - filemtime($a);
});
// Pagination
$total_posts = count($files);
$total_pages = ceil($total_posts / $posts_per_page);
// Get current page from query parameter
$current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($current_page < 1) $current_page = 1;
if ($current_page > $total_pages) $current_page = $total_pages;
// Calculate the offset
$offset = ($current_page - 1) * $posts_per_page;
// Slice the array of files for the current page
$files = array_slice($files, $offset, $posts_per_page);
$parsedown = new Parsedown();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My PHP Blog</title>
<!-- Include highlight.js CSS -->
<link rel="stylesheet" href="assets/highlight/styles/default.css">
<!-- Include your custom CSS -->
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<h1>My Blog</h1>
<?php
foreach ($files as $file) {
$content = file_get_contents($file);
// Separate YAML front matter and Markdown content
if (preg_match('/^---(.*?)---(.*)/s', $content, $matches)) {
$yaml = parseYAML(trim($matches[1]));
$md_content = trim($matches[2]);
} else {
$yaml = [];
$md_content = $content;
}
// Extract the content before the readmore tag
$content_parts = explode('<!--readmore-->', $md_content);
$intro = $content_parts[0];
$full_content = $md_content;
// Parse Markdown
$html_intro = $parsedown->text($intro);
$html_full = $parsedown->text($full_content);
// Display the post
echo '<div class="post">';
echo '<h2>' . htmlspecialchars($yaml['title'] ?? 'Untitled') . '</h2>';
echo '<p class="date">' . htmlspecialchars($yaml['date'] ?? '') . '</p>';
echo $html_intro;
if (count($content_parts) > 1) {
// There's more content after the readmore tag
echo '<p><a href="post.php?file=' . urlencode(basename($file)) . '">Read more...</a></p>';
}
echo '</div>';
}
?>
<!-- Pagination -->
<div class="pagination">
<?php if ($current_page > 1): ?>
<a href="?page=<?php echo ($current_page - 1); ?>">« Previous</a>
<?php endif; ?>
<?php if ($current_page < $total_pages): ?>
<a href="?page=<?php echo ($current_page + 1); ?>">Next »</a>
<?php endif; ?>
</div>
<!-- Include highlight.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
<script>hljs.highlightAll();</script>
</body>
</html>
Explanation
Include Libraries: We include Parsedown.php for Markdown parsing and YAMLParser.php for parsing the YAML front matter.
Read Markdown Files: We get all .md files from the posts/ directory.
Sorting: We sort the files by their modification time to display the newest posts first.
Pagination: Calculate the total number of pages and slice the array of files to get posts for the current page.
Parsing Posts:
Use a regular expression to separate the YAML front matter and the Markdown content.
Use explode('<!--readmore-->') to split the content at the <!--readmore--> tag.
Parse the intro content to HTML for display on the index page.
Display Posts: Output the post title, date, and intro content. If the post has more content, display a "Read more..." link.
Pagination Links: Display "Previous" and "Next" links for pagination.
Integrate highlight.js: Include the script and initialize it with hljs.highlightAll();.
5. Create a Post Page to Display Full Posts
Create a post.php to display the full content of a single post.
post.php
php
<?php
// Include Parsedown and YAML parser
include_once 'includes/Parsedown.php';
include_once 'includes/YAMLParser.php';
$posts_dir = 'posts/';
if (!isset($_GET['file'])) {
echo 'No post specified.';
exit;
}
$file = basename($_GET['file']);
$file_path = $posts_dir . $file;
if (!file_exists($file_path)) {
echo 'Post not found.';
exit;
}
$content = file_get_contents($file_path);
// Separate YAML front matter and Markdown content
if (preg_match('/^---(.*?)---(.*)/s', $content, $matches)) {
$yaml = parseYAML(trim($matches[1]));
$md_content = trim($matches[2]);
} else {
$yaml = [];
$md_content = $content;
}
$parsedown = new Parsedown();
$html_content = $parsedown->text($md_content);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo htmlspecialchars($yaml['title'] ?? 'Untitled'); ?></title>
<!-- Include highlight.js CSS -->
<link rel="stylesheet" href="assets/highlight/styles/default.css">
<!-- Include your custom CSS -->
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<h1><?php echo htmlspecialchars($yaml['title'] ?? 'Untitled'); ?></h1>
<p class="date"><?php echo htmlspecialchars($yaml['date'] ?? ''); ?></p>
<?php echo $html_content; ?>
<p><a href="index.php">Back to Blog</a></p>
<!-- Include highlight.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
<script>hljs.highlightAll();</script>
</body>
</html>
Explanation
We retrieve the specific post based on the file query parameter.
We read and parse the content similar to index.php.
Display the full content of the post.
Provide a link back to the main blog page.
6. Integrate highlight.js
To enable syntax highlighting in your code blocks:
Download highlight.js or use a CDN link.
Include the CSS in the <head> section.
Include the JS script before the closing </body> tag.
We've used the CDN links in the above code.
Example Code Block in Markdown
markdown
Here is some JavaScript code:
```javascript
function helloWorld() {
console.log('Hello, world!');
}
\```
7. Styling with CSS
Create a CSS file assets/css/style.css to style your blog.
Create multiple Markdown files in the posts/ directory with YAML front matter and content.
Include <!--readmore--> in some posts to test truncation.
Ensure code blocks in your posts are highlighted correctly.
Conclusion
You've now created a flat-file PHP blog that reads Markdown posts from the /posts directory, uses Parsedown.php for Markdown parsing, integrates highlight.js for syntax highlighting, supports pagination, and implements <!--readmore--> for post truncation. The YAML parser allows you to include metadata in your posts.
Note: Be sure to handle security aspects such as input validation and output escaping to prevent potential vulnerabilities like XSS attacks. Always sanitize user inputs and encode outputs appropriately.