Backing up my blog
Using the hooks provided by Pure Blog I was able to set up my blog to automatically commit and push my /content directory to a private repo to keep a backup of all of my content in the event of a disaster on my VPS. The VPS also takes nightly backups but off-site backups are also a good idea.
Below is my /config/hooks.php file which defines a simple function that sets a target directory and builds a few git commands to execute. Then calls the function in the publish, update and delete hooks.
The only thing other than this that I needed was to create an ssh key for my Pure Blog user and get that set up with the git repo so it can push without needing a password.
<?php
function pureblog_auto_backup_git(string $action, string $slug): void
{
$postsDir = __DIR__ . '/../content/posts';
// Check if the directory exists and is a git repository
if (!is_dir($postsDir . '/.git')) {
error_log("PureBlog Hook: $postsDir is not a valid git repository.");
return;
}
$currentUser = shell_exec('whoami');
error_log("PureBlog git executing user is: " . trim($currentUser));
$command = sprintf(
'cd %s && git add . && git commit -m "Auto-backup: %s post %s by user %s" && git push',
escapeshellarg($postsDir),
escapeshellarg($action),
escapeshellarg($slug),
escapeshellarg($currentUser)
);
// Execute the command, redirecting output to the null device to prevent it from hanging the process
exec($command . ' > /dev/null 2>&1 &', $output, $resultCode);
}
function on_post_published(string $slug): void
{
pureblog_auto_backup_git('publish', $slug);
}
function on_post_updated(string $slug): void
{
pureblog_auto_backup_git('update', $slug);
}
function on_post_deleted(string $slug): void
{
pureblog_auto_backup_git('delete', $slug);
}