This site uses third-party cookies, learn more or accept
dark light

Create a PHP Blog - no Database Needed!

Written by Max Pelic on

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:

1<!doctype html>

2<html>
3 <head>
4 <title>Create a Blog Post</title>
5 </head>
6 <body>
7 <form method=post>
8 <input name="title">
9 <textarea name="content">
10 <input name="path"><!-- path we'll use to view the blog bost -->
11 <button type="submit">Save</button>
12 </form>
13 </body>
14</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:

1<?php

2
3#check if form was submitted
4

5if(isset($_POST["title"])){
6
7 #get the values submitted
8
$title = $_POST["title"];
9 $content = $_POST["content"];
10
11 #only allow letters, numbers, dashes and underscores in the path
12
$path = strtolower(preg_replace('/[^0-9a-zA-Z-_]/', '', $_POST["path"]));
13
14 #at this point we'll save a new file with the blog post data in JSON format
15
$json = json_encode([
16 "title"=>$title,
17 "content"=>$content
18 ]);
19
20 #save the json data in a file in the "files" folder
21
file_put_contents("files/" . $path . ".json", $json);
22
23 #Your blog post is now saved!
24

25}
26
27?>

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:

1<?php

2
3#we'll use the url parameter "post-id" to get the file path
4
$path = $_GET['post-id'];
5
6#let's serialize the path to prevent people from opening other files we don't want them to open
7
#we'll use the same code we used on the create.php page
8
$path = strtolower(preg_replace('/[^0-9a-zA-Z-_]/', '', $_POST["path"]));
9
10#now we can open the json file and read the contents
11
$filePath = "files/" . $path . ".json";
12$data = [];
13
14if(file_exists($filePath)){
15
16 $data = json_decode(file_get_contents($filepPath));
17
18} else {
19 #handle errors here
20
echo "Post not found";
21 exit;
22}
23?>

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.

1<!doctype html>

2<html>
3 <head>
4 <title><?php echo htmlspecialchars($data->title); ?></title>
5 </head>
6 <body>
7 <article>
8 <h1><?php echo htmlspecialchars($data->title); ?></h1>
9 <p>
10 <!-- replace newline chars with closing and opening paragraph tags -->
11 <?php echo preg_replace("/\\n/", "</p><p>", htmlspecialchars($data->content)); ?>
12 </p>
13 </article>
14 </body>
15</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:

1<?php

2
3$files = glob("files/*.json");
4
5#sort the files by the date they were created
6
usort($files, function($a, $b) {
7 return filectime($a) < filectime($b);
8});
9
10?>

Now let's use some HTML and PHP to create a list of the files we got:

1<!doctype html>

2 <head>
3 <title>My Blog Feed</title>
4 </head>
5 <body>
6<?php
7
8foreach($files as $file){
9
10 $data = json_decode(file_get_contents($file));
11
12 $filePath = basename($file, '.json');
13
14 echo '<a href="view.php?post-id=' . $filePath . '">';
15
16 echo '<h1>' . htmlspecialchars($data->title) . '</h1>';
17
18 echo '</a>';
19
20}
21
22?>
23 </body>
24</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:

1#require basic http authentication, built in to most browsers

2
if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] !== 'your-username' || $_SERVER['PHP_AUTH_PW'] !== 'your-password') {
3 header('WWW-Authenticate: Basic realm="Blog Post"');
4 header('HTTP/1.0 401 Unauthorized');
5 echo 'Go away';
6 exit;
7}

Here's all the completed files:

create.php

1<?php

2
3#require basic http authentication, built in to most browsers
4
if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] !== 'your-username' || $_SERVER['PHP_AUTH_PW'] !== 'your-password') {
5 header('WWW-Authenticate: Basic realm="Blog Post"');
6 header('HTTP/1.0 401 Unauthorized');
7 echo 'Go away';
8 exit;
9}
10
11#check if form was submitted
12

13if(isset($_POST["title"])){
14
15 #get the values submitted
16
$title = $_POST["title"];
17 $content = $_POST["content"];
18
19 #only allow letters, numbers, dashes and underscores in the path
20
$path = strtolower(preg_replace('/[^0-9a-zA-Z-_]/', '', $_POST["path"]));
21
22 #at this point we'll save a new file with the blog post data in JSON format
23
$json = json_encode([
24 "title"=>$title,
25 "content"=>$content
26 ]);
27
28 #save the json data in a file in the "files" folder
29
file_put_contents("files/" . $path . ".json", $json);
30
31 #Your blog post is now saved!
32

33}
34
35?>
36
37<!doctype html>
38<html>
39 <head>
40 <title>Create a Blog Post</title>
41 </head>
42 <body>
43 <form method=post>
44 <input name="title">
45 <textarea name="content">
46 <input name="path"><!-- path we'll use to view the blog bost -->
47 <button type="submit">Save</button>
48 </form>
49 </body>
50</html>

view.php

1<?php

2
3#we'll use the url parameter "post-id" to get the file path
4
$path = $_GET['post-id'];
5
6#let's serialize the path to prevent people from opening other files we don't want them to open
7
#we'll use the same code we used on the create.php page
8
$path = strtolower(preg_replace('/[^0-9a-zA-Z-_]/', '', $_POST["path"]));
9
10#now we can open the json file and read the contents
11
$filePath = "files/" . $path . ".json";
12$data = [];
13
14if(file_exists($filePath)){
15
16 $data = json_decode(file_get_contents($filepPath));
17
18} else {
19 #handle errors here
20
echo "Post not found";
21 exit;
22}
23?>
24<!doctype html>
25<html>
26 <head>
27 <title><?php echo htmlspecialchars($data->title); ?></title>
28 </head>
29 <body>
30 <article>
31 <h1><?php echo htmlspecialchars($data->title); ?></h1>
32 <p>
33 <!-- replace newline chars with closing and opening paragraph tags -->
34 <?php echo preg_replace("/\\n/", "</p><p>", htmlspecialchars($data->content)); ?>
35 </p>
36 </article>
37 </body>
38</html>

index.php

1<?php

2
3$files = glob("files/*.json");
4
5#sort the files by the date they were created
6
usort($files, function($a, $b) {
7 return filectime($a) < filectime($b);
8});
9
10?>
11<!doctype html>
12 <head>
13 <title>My Blog Feed</title>
14 </head>
15 <body>
16<?php
17
18foreach($files as $file){
19
20 $data = json_decode(file_get_contents($file));
21
22 $filePath = basename($file, '.json');
23
24 echo '<a href="view.php?post-id=' . $filePath . '">';
25
26 echo '<h1>' . htmlspecialchars($data->title) . '</h1>';
27
28 echo '</a>';
29
30}
31
32?>
33 </body>
34</html>

That's it, you now have a PHP blog! Now start writing posts and watch your blog grow!

Share this article:

Previous Article: 3 Ways to Include Files on Your Website

Next Article: Host a free static site with GitHub Pages