How to get a path to the date and extension of a file using some PHP function

Asked

Viewed 45 times

0

I have an array with two types of files: .jpg and .pdf. I’m developing a PHP page of monthly publications.

I created a select to define the year of publication, the user will be able to choose the year of publication, type: when choosing the year 2018, automatically will appear all the covers of the publications of each month of the year 2018 in a <img>, by clicking on the publication image I would like you to open another page in the browser downloading the PDF of the publication.

In the following code, I can bring all the files in .jpg and .pdf. I just can’t develop how to get these files in the array and reallocate the .jpg on the page and the .pdf to download.

Code:

<center>
<div>
    <h3>Publicações</h3>
        <div>
            <form id="formConsulta" action="arquivo.php" method="post" name="formConsulta">
                <select name="slcAnoFalaBrt">
                    <option value='2012'>2012</option>
                    <option value='xxx'>xxx</option>
                   <option value='2019'>2019</option>
               </select>
                <input type="submit" value="Buscar">
            </form>
        </div>
        <br>
        <div>

        </div>
</div>




<?php

if(isset($_POST['slcAno'])){

$intAno = $_POST['slcAno'];

//Obter a listagem dos Arquivos do diretório
$pasta = 'download/Publicacoes/';


if(is_dir($pasta)){
  $diretorio = dir($pasta);
  //var_dump($diretorio);//

  while($arquivo = $diretorio->read()){
    if($arquivo != '..' && $arquivo != '.'){
        // Cria um Array com todos os Arquivos encontrados
    $arrayArquivos[date('Y/m/d H:i:s', filemtime($pasta.$arquivo))] =   $pasta.$arquivo;


    }//fim if//
    }//fim while//

  $diretorio->close();
}//fim if is_dir();//

//Classificar os  arquivos para a Ordem Crescente
//krsort($arrayArquivos, SORT_STRING);

//Mostra a listagem dos Arquivos
foreach($arrayArquivos as $valorArquivos ){

echo '<a href='.$valorArquivos.'>'.$valorArquivos.'</a><br />';//


}//fim foreach

}//fim if isset//

?>
  • Guys, I don’t know how to leave the code formatted in the Stack overflow pattern! Could someone help!

  • 1

    PCP84, in the editor there are two keys {}, select your code and click on it. :)

  • 1

    I formatted the code. To learn how to do it, see help center

  • Because you use the date date('Y/m/d H:i:s', filemtime($pasta.$arquivo)) in the array index? And when you use $intAno?

  • int year and to select the year of publication, and date('Y/m/d H:i:s', filemtime($folder. $file)) the idea and to compare the file date. (if user selects year 2018 print on screen only 2018 publications!

1 answer

1

I made some modifications in your code that should work (I have not tested), the explanation is in the comments of the code, but basically I grouped the files by mes e ano and then I went into each group picking up the file guy with pathinfo().

*** The lines marked with /* ****** */ have undergone some modification.

EDIT: I added a filter to ignore files that are not of the desired year.

      <?php

    if (isset($_POST['slcAno'])) {

        $intAno = $_POST['slcAno'];
/* * */ $arrayArquivos = [];
        //Obter a listagem dos Arquivos do diretório
        $pasta = 'download/Publicacoes/';


        if (is_dir($pasta)) {
            $diretorio = dir($pasta);
            //var_dump($diretorio);//

            while ($arquivo = $diretorio->read()) {
                if ($arquivo != '..' && $arquivo != '.') {
                    // Cria um Array com todos os Arquivos encontrados
    /* ********** */ $fileTime = filemtime($pasta . $arquivo);
    /* ********** */ $fileYear = date('Y', $fileTime );
    /* ********** */ if($fileYear == $intAno){
    /* ********** */    $arrayArquivos[date('Ym', $fileTime)][] =   $pasta . $arquivo; //deve conter 1 pdf e um jpeg (que são do mesmo mes)
    /* ********** */ }
                } //fim if//
            } //fim while//

            $diretorio->close();
        } //fim if is_dir();//

        //Classificar os  arquivos para a Ordem Crescente
        //krsort($arrayArquivos, SORT_STRING);

        //Mostra a listagem dos Arquivos


        foreach ($arrayArquivos as $valorArquivos) {

    /* ****** */ $img = "";
    /* ****** */ $pdf = "";
    /* ****** */ //verifica se o caminho salvo no mes especificado é pdf ou outro
    /* ****** */ foreach($valorArquivos as $arquivo){
    /* ****** */     if(pathinfo($arquivo)['extension'] == "pdf"){
    /* ****** */         $pdf = $arquivo;
    /* ****** */     }else{
    /* ****** */         $img = $arquivo;
    /* ****** */     }
    /* ****** */ }
    /* ****** */ echo '<a href=' . $pdf . '>' . $img . '</a><br />'; //


        } //fim foreach

    }//fim if isset//
  • Didn’t work @Edson Alves ! is returning the same jpg and pdf when selecting any year!

  • The part I moved was to separate pdf and jpeg. I will change to bring only the chosen year.

  • Forehead now to see

  • is giving error in the $arrayArchives variable ( Undefined variable: arrayArchives in /path...) and Invalid argument supplied for foreach().

  • What version of your php? Try now, I started the variable $arrayArquivos = [];

  • Current PHP version: 7.0.30. I did the test here and it didn’t work!

  • You can add the error you gave now?

  • nothing happens! The page loads but does not return any image

  • Try, I was returning empty because $fileTime == $intAno would never be true, the correct is $fileYear == $intAno

Show 4 more comments

Browser other questions tagged

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