Delete file in php at specified frequency

Asked

Viewed 1,497 times

1

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

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 are more than 3 months old. I can’t 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)

  • 2

    Linux or Windows server?

  • windows server

  • 1

    3 months since creation?

  • 1

    This. An upload will be made to a particular folder. This script would only check from the date of the upload of that file to the folder. If you had more than 3 months in the folder, it would delete the file, otherwise it would do nothing.

  • 2

    If at the time of upload you can save the date of when it was made, it is more reliable that fileatime(). To run this periodically you can use the cronjob or windows task scheduler

  • I’ve heard of cronjob, but I’ve never used it yet. I’ll try to learn how to use it.

Show 1 more comment

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 (source).

In your example you used fileatime(), which obtains the date of the last access, but by the 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
}
  • Sanction, I even forgot to put the following comment on the question: Is there a way to do this automatically? I tested your code here and it came right!!!

  • 1

    Well, in the end AP will have to test what is best in his case, it depends a lot on how the files are generated. Anyway, the way to solve you is over.

  • Good guys, thank you, you’ve helped me a lot!

2

complementing the response of Sanction, follow 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();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.