Skip to content

Instantly share code, notes, and snippets.

@ProjectOrangeBox
Last active June 11, 2020 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ProjectOrangeBox/f35ddedf52246c0cec897ba8ffc63402 to your computer and use it in GitHub Desktop.
Save ProjectOrangeBox/f35ddedf52246c0cec897ba8ffc63402 to your computer and use it in GitHub Desktop.
Clean up files in a folder based on regular expression and days as well as database table based on datetime stamp
<?php
class cleanUp
{
static public function folder(string $folder, string $fileRegEx, int $days, bool $recusive = true): int
{
$count = 0;
if (!\FS::file_exists($folder)) {
throw new \Exception('Folder "' . $folder . '" not found.');
}
$fileRegEx = ';' . str_replace(';', '\;', $fileRegEx) . ';';
foreach (FS::glob(rtrim($folder, '/') . '/*', 0, $recusive) as $singleFile) {
if (preg_match($fileRegEx, FS::basename($singleFile))) {
if (time() - FS::filemtime($singleFile) >= (86400 * $days)) {
FS::unlink($singleFile);
$count++;
}
}
}
return $count;
}
static public function table(string $pdoDSN, string $username, string $password, string $tableColumn, int $days): int
{
$count = 0;
try {
$pdo = new PDO($pdoDSN, $username, $password);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int) $e->getCode());
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
list($table, $column) = explode('.', $tableColumn, 2);
try {
$del = $pdo->prepare('delete from `' . $table . '` where `' . $column . '` < NOW() - INTERVAL ? DAY');
$del->execute([$days]);
$count = $del->rowCount();
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int) $e->getCode());
}
return $count;
}
} /* end class */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment