Get name of a csv file

1

In a site that I develop I backup data in csv my problem and if I want to recover the backup (through the site) as I have a folder with several csv I can not know what was the last one that was created. p>

Does anyone know of any way I can check the date in the name because the file name is from this genre name_2015-11-13_01.42.22_.csv

Thank you

    
asked by anonymous 13.11.2015 / 13:44

3 answers

2

Use the glob () function to list all csv files, done so get the date contained in the name, with the explode () the index containing the da is the 1 and the time 2 , change the . by : , add this new string in the $novo array then decently decrypt with rsort ()

<?php
error_reporting(E_ALL|E_STRICT);

$arquivos = glob('temp/*.csv');
$novo = array();
foreach ($arquivos as $item){
    $datahora = explode('_', $item);
    $novo[] = $datahora[1] .' '. str_replace('.', ':', $datahora[2]);
}

rsort($novo);
$backup = array_shift($novo);
echo 'Backup mais recente realizado em: '.  $backup;

The output is something like:

Array
(
    [0] => 2015-11-14 01:42:23
    [1] => 2015-11-14 01:42:22
    [2] => 2015-11-13 01:42:22
    [3] => 2015-11-12 01:42:22
    [4] => 2015-11-10 01:42:22
    [5] => 2015-10-13 01:42:22
)
Backup mais recente realizado em 2015-11-14 01:42:23
    
13.11.2015 / 14:22
1

Scroll through the directory of your backups and sort the files by creation date.

<?php

$arquivos = array();
$diretorio = 'caminho/da/pasta/de/backup/';
$manipulador  = opendir($dir);
while (false !== ($arquivo = readdir($manipulador))) {
    $arquivos[] = $arquivo;
}

$listaArquivos = array();
foreach ($arquivos as $arquivo) {
    $listaArquivos[filemtime($arquivo)] = $arquivo;
}

ksort($listaArquivos);
var_dump($listaArquivos);

?>
    
13.11.2015 / 14:15
1

To list the files exists in more ways, as pointed out in the other answers.

In any case, you will have to extract the portion that refers to the date, position, or regular expression.

$arquivo = 'nome_2015-11-13_01.42.22_.csv';
$prefixo = 'nome_';
$dataHora = substr(strlen($prefixo), 19);

To convert to date you have two ways:

1 - with the function DateTime::createFromFormat (PHP required = 5.3.0), in this case an object will be returned DateTime

DateTime::createFromFormat('Y-m-d_H.i.s', $dataHora)

2 - with strtotime , you will need to convert the format, changing the _ by T , according to the [compound formats] accepted, which returns a time stamp : / p>

strtotime($dataHora, str_replace('_', 'T', $dataHora));
    
13.11.2015 / 14:24