Delete file in php with determined frequency

1

I've been trying to do a function that could delete files from within a given directory according to an informed date. In this example I have not yet created the function because I am still trying to understand how it is done.

echo "<br />";
$arquivo = 'documento.pdf';
if(date("November 05 2016 19:19:24.", fileatime($arquivo))){
    echo "Excluiu!";
    unlink($arquivo);
} else {
    echo "Não excluiu!";
} 

A very basic example of what I'm trying to do is delete files from a folder that have been in it for more than 3 months. I can not understand how I can spend this time and use it as a parameter in a function (because I can change the time if I need to)

    
asked by anonymous 05.11.2015 / 19:35

2 answers

3

You can use strtotime() to set the time from a period and compare with the result of filectime() , which returns the creation date on Windows servers ( font ).

In your example, you used fileatime() , which gets the last access date, but for description of the problem the correct one is to use filectime() , but can be changed according to the desired behavior.

// a data de criação é anterior à 3 meses atrás
if (filectime($arquivo) < strtotime('-3 month')) {
  // apagar
}
    
05.11.2015 / 19:51
2

Complementing the Sanction response, follows PHP code to list all files in the directory:

//diretório que deseja listar os arquivos
$path = "arquivos/";

//le os arquivos do diretorio
$diretorio = dir($path);

//loop para listar os arquivos do diretório, guardando na variável $arquivo
while( $arquivo = $diretorio -> read() ){

  //gera um link para o arquivo
  echo "<a href='".$path.$arquivo."'>".$arquivo."</a><br />"; 
}
$diretorio -> close();
    
06.11.2015 / 04:22