Create a PHP Blog - no Database Needed!
Wouldn’t it be nice to have a blog, without having to worry about hosting and maintaining a database? With PHP, you can easily make one!
Let’s start by making a page where we can create blog posts. We’ll call this file create.php
and put it in our root directory. The first step is to create a form in this file where we can type out our blog post:
<!doctype html>
<html>
<head>
<title>Create a Blog Post</title>
</head>
<body>
<form method=post>
<input name="title">
<textarea name="content">
<input name="path"><!-- path we'll use to view the blog bost -->
<button type="submit">Save</button>
</form>
</body>
</html>
We’ll use this page to create posts, and we’ll also use it to save the posts. So let’s add some PHP
code at the top that saves the posts when we submit the form:
<?php
#check if form was submitted
if(isset($_POST["title"])){
#get the values submitted
$title = $_POST["title"];
$content = $_POST["content"];
#only allow letters, numbers, dashes and underscores in the path
$path = strtolower(preg_replace('/[^0-9a-zA-Z-_]/', '', $_POST["path"]));
#at this point we'll save a new file with the blog post data in JSON format
$json = json_encode([
"title"=>$title,
"content"=>$content
]);
#save the json data in a file in the "files" folder
file_put_contents("files/" . $path . ".json", $json);
#Your blog post is now saved!
}
?>
So now we have a way to write and save blog posts, now lets create a file to view them. We’ll worry about adding security to the create.php
page later.
Let’s create a file called view.php
to view our blog posts. In the that file, we’ll need to check which post is being viewed, open that json file, and output the contents on the page.
At the start of the file, lets load the file:
<?php
#we'll use the url parameter "post-id" to get the file path
$path = $_GET['post-id'];
#let's serialize the path to prevent people from opening other files we don't want them to open
#we'll use the same code we used on the create.php page
$path = strtolower(preg_replace('/[^0-9a-zA-Z-_]/', '', $_POST["path"]));
#now we can open the json file and read the contents
$filePath = "files/" . $path . ".json";
$data = [];
if(file_exists($filePath)){
$data = json_decode(file_get_contents($filepPath));
} else {
#handle errors here
echo "Post not found";
exit;
}
?>
For the last part of the posts page, we’ll use a combination of html and PHP to show the blog post to the visitor.
<!doctype html>
<html>
<head>
<title><?php echo htmlspecialchars($data->title); ?></title>
</head>
<body>
<article>
<h1><?php echo htmlspecialchars($data->title); ?></h1>
<p>
<!-- replace newline chars with closing and opening paragraph tags -->
<?php echo preg_replace("/\\n/", "</p><p>", htmlspecialchars($data->content)); ?>
</p>
</article>
</body>
</html>
There we go - we now have a way to access posts! To view a post, you can just visit /view.php?post-id=path-to-post
!
Last but not least, let’s make an index.php
page to view a list of all the posts. We’ll start by getting an array of all the json files using the glob
function, then we’ll add some html to view all the posts.
First, here’s the code to get all the posts:
<?php
$files = glob("files/*.json");
#sort the files by the date they were created
usort($files, function($a, $b) {
return filectime($a) < filectime($b);
});
?>
Now let’s use some HTML and PHP to create a list of the files we got:
<!doctype html>
<head>
<title>My Blog Feed</title>
</head>
<body>
<?php
foreach($files as $file){
$data = json_decode(file_get_contents($file));
$filePath = basename($file, '.json');
echo '<a href="view.php?post-id=' . $filePath . '">';
echo '<h1>' . htmlspecialchars($data->title) . '</h1>';
echo '</a>';
}
?>
</body>
</html>
Now when someone visits your site they will see a list of all your blog posts.
The last step is securing your create.php
file. Let’s go back to that and add this php code at the top:
#require basic http authentication, built in to most browsers
if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] !== 'your-username' || $_SERVER['PHP_AUTH_PW'] !== 'your-password') {
header('WWW-Authenticate: Basic realm="Blog Post"');
header('HTTP/1.0 401 Unauthorized');
echo 'Go away';
exit;
}
Here’s all the completed files:
create.php
<?php
#require basic http authentication, built in to most browsers
if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] !== 'your-username' || $_SERVER['PHP_AUTH_PW'] !== 'your-password') {
header('WWW-Authenticate: Basic realm="Blog Post"');
header('HTTP/1.0 401 Unauthorized');
echo 'Go away';
exit;
}
#check if form was submitted
if(isset($_POST["title"])){
#get the values submitted
$title = $_POST["title"];
$content = $_POST["content"];
#only allow letters, numbers, dashes and underscores in the path
$path = strtolower(preg_replace('/[^0-9a-zA-Z-_]/', '', $_POST["path"]));
#at this point we'll save a new file with the blog post data in JSON format
$json = json_encode([
"title"=>$title,
"content"=>$content
]);
#save the json data in a file in the "files" folder
file_put_contents("files/" . $path . ".json", $json);
#Your blog post is now saved!
}
?>
<!doctype html>
<html>
<head>
<title>Create a Blog Post</title>
</head>
<body>
<form method=post>
<input name="title">
<textarea name="content">
<input name="path"><!-- path we'll use to view the blog bost -->
<button type="submit">Save</button>
</form>
</body>
</html>
view.php
<?php
#we'll use the url parameter "post-id" to get the file path
$path = $_GET['post-id'];
#let's serialize the path to prevent people from opening other files we don't want them to open
#we'll use the same code we used on the create.php page
$path = strtolower(preg_replace('/[^0-9a-zA-Z-_]/', '', $_POST["path"]));
#now we can open the json file and read the contents
$filePath = "files/" . $path . ".json";
$data = [];
if(file_exists($filePath)){
$data = json_decode(file_get_contents($filepPath));
} else {
#handle errors here
echo "Post not found";
exit;
}
?>
<!doctype html>
<html>
<head>
<title><?php echo htmlspecialchars($data->title); ?></title>
</head>
<body>
<article>
<h1><?php echo htmlspecialchars($data->title); ?></h1>
<p>
<!-- replace newline chars with closing and opening paragraph tags -->
<?php echo preg_replace("/\\n/", "</p><p>", htmlspecialchars($data->content)); ?>
</p>
</article>
</body>
</html>
index.php
<?php
$files = glob("files/*.json");
#sort the files by the date they were created
usort($files, function($a, $b) {
return filectime($a) < filectime($b);
});
?>
<!doctype html>
<head>
<title>My Blog Feed</title>
</head>
<body>
<?php
foreach($files as $file){
$data = json_decode(file_get_contents($file));
$filePath = basename($file, '.json');
echo '<a href="view.php?post-id=' . $filePath . '">';
echo '<h1>' . htmlspecialchars($data->title) . '</h1>';
echo '</a>';
}
?>
</body>
</html>
That’s it, you now have a PHP blog! Now start writing posts and watch your blog grow!