Reputation: 93
I'm trying to create 4 scripts which will make the fallowing tasks:
Below is the code I found online. So I created 4 separate files like script1.php and so on, uploaded on my server and tried to fire them up. All I have returned is the code itself in the browser window, but files and folders are not deleted:( Hope you can help me on that. Below I tried to adopt the code I found online and create 3 scripts. Unfortunately I have no idea how to create the 4th one as it will be more complicated.
I'm only a front end developer started to learn the PHP code basics...
/***** SCRIPT 1 - Delete files older than 21 days with .txt extension *****/
$days = 21;
$path = './mypath/folder_with_txt_files/';
$filetypes_to_delete = array("txt");
if ($handle = opendir($path))
{
while (false !== ($file = readdir($handle)))
{
if (is_file($path.$file))
{
$file_info = pathinfo($path.$file);
if (isset($file_info['extension']) && in_array(strtolower($file_info['extension']), $filetypes_to_delete))
{
if (filemtime($path.$file) < ( time() - ( $days * 24 * 60 * 60 ) ) )
{
unlink($path.$file);
}
}
}
}
}
/***** SCRIPT 2 - Delete folders older than 21 days *****/
$days = 21;
$path = './mypath/folders_to_delete/';
if ($handle = opendir($path))
{
while (false !== ($file = readdir($handle)))
{
if (is_dir($path.$file))
{
if (filemtime($path.$file) < ( time() - ( $days * 24 * 60 * 60 ) ) )
{
unlink($path.$file);
}
}
}
}
/***** SCRIPT 3 - Delete files older than 21 days *****/
$days = 21;
$path = '/mypath/folder_with_files_to_delete';
if ($handle = opendir($path))
{
while (false !== ($file = readdir($handle)))
{
if (is_file($path.$file))
{
if (filemtime($path.$file) < ( time() - ( $days * 24 * 60 * 60 ) ) )
{
unlink($path.$file);
}
}
}
}
/***** SCRIPT 4 - Delete files inside the folder and subfolders older than 21 days with prefix 'file_prefix' *****/
?
Upvotes: 3
Views: 1333
Reputation: 1069
The webserver tries hard to isolate its working from that of the operating system, for evident security reasons. The webserver itself normally runs under a very strict and limited user account.
For running maintenance scripts via the browser you need to undo these protections and give the webserver permissions over more folders.
This would be a very bad idea.
You may however run these scripts from the command-line version of PHP, meaning from the console. It would then have the same permissions as inherited from the console.
Upvotes: 1