backup.php 1.12 KB
Newer Older
David Morley's avatar
David Morley committed
1
<?php
2

3 4 5 6 7 8
/**
 * Backup / dump PostgreSQL database.
 */

declare(strict_types=1);

David Morley's avatar
David Morley committed
9 10 11
require_once __DIR__ . '/../boot.php';

if (!is_cli()) {
12 13
    header('HTTP/1.0 403 Forbidden');
    exit;
14 15
}

David Morley's avatar
David Morley committed
16 17 18 19 20 21 22 23 24 25 26 27 28 29
$keep_for    = 60 * 60 * 6; // 6 hours
$backup_file = c('backup_dir') . '/dump_' . date('Ymd_His') . '.sql';

printf("Making backup of '%s' to '%s'...", c('pgdb'), $backup_file);
system(sprintf(
    'export PGPASSWORD=%3$s &&' .
    '"%1$s" --clean --format=tar --username=%2$s %4$s >> "%5$s"',
    c('pg_dump_dir') . '/pg_dump',
    c('pguser'),
    c('pgpass'),
    c('pgdb'),
    $backup_file
), $exit_code);
printf(" %s\n", $exit_code === 0 ? 'Success!' : 'Failed.');
30

David Morley's avatar
David Morley committed
31
$dirh = dir(c('backup_dir'));
32
while ($entry = $dirh->read()) {
David Morley's avatar
David Morley committed
33 34 35 36 37
    $file = c('backup_dir') . "/{$entry}";

    // Skip dotfiles and non-files (folders, symlinks, etc.).
    if ($entry[0] === '.' || !is_file($file)) {
        continue;
David Morley's avatar
David Morley committed
38
    }
David Morley's avatar
David Morley committed
39 40 41 42 43 44 45 46 47 48 49

    if (filectime($file) + $keep_for > time()) {
        //echo "Don't delete {$entry}\n";
        continue;
    }

    printf(
        "Removing old file '%s'... %s\n",
        $entry,
        unlink($file) ? 'Success!' : 'Failed.'
    );
David Morley's avatar
David Morley committed
50
}