Doubt about else within a foreach

0

Gentlemen, cordial greetings.

Searching, I found on the network a php script that allows me to search for files in a directory, I made an adjustment so that I search only pdf files and show me a link to download it, this works well, but I would like to show a % error echo if the file is not found, I could not locate the echo correctly so that it does not repeat.

        <?php

        // Ruta del directorio donde están los archivos
        $path  = 'C:\wamp\www\buscador'; 

        // Arreglo con todos los nombres de los archivos
        $files = array_diff(scandir($path), array('.', '..')); 

        // Obtienes tu variable mediante GET
        $code = $_GET['codigo'];

    foreach($files as $file){
        // Divides en dos el nombre de tu archivo utilizando el . 
        $data          = explode(".", $file);
        // Nombre del archivo
        $fileName      = $data[0];
        // Extensión del archivo 
        $fileExtension = $data[1];

        if($code == $fileName){
            echo "<a href = '$fileName.pdf' >Descargar certificado</a>";
            break;  // Realizamos un break para que el ciclo se interrumpa
    }    
} 

?>
    
asked by Juan Carlos Monsalve 12.11.2018 в 17:29
source

2 answers

1

You can create a variable that tells you if the file you are looking for has been found or not. You create the variable with an initial value of False and in case you find the file you set it to true. The check of the variable is done outside the loop so that the message is not repeated.

        <?php

    // Ruta del directorio donde están los archivos
    $path  = 'C:\wamp\www\buscador'; 

    // Arreglo con todos los nombres de los archivos
    $files = array_diff(scandir($path), array('.', '..')); 

    // Obtienes tu variable mediante GET
    $code = $_GET['codigo'];
    $existFile = false;


foreach($files as $file){
    // Divides en dos el nombre de tu archivo utilizando el . 
    $data          = explode(".", $file);
    // Nombre del archivo
    $fileName      = $data[0];
    // Extensión del archivo 
    $fileExtension = $data[1];

    if($code == $fileName){
        $existFile = true;
        echo "<a href = '$fileName.pdf' >Descargar certificado</a>";
        break;  // Realizamos un break para que el ciclo se interrumpa
    }    
}
if ($existFile == false){
     echo "<p> No se ha encontrado el fichero </p>";         
}

? >

I hope it serves you.

    
answered by 12.11.2018 / 17:39
source
0

Apparently the place to paint a echo error would be in a else added to if that paints the link if the content of $code equals the content of $fileName . It would be something like this:

if($code == $fileName){
    echo "<a href = '$fileName.pdf' >Descargar certificado</a>";
    break;  // Realizamos un break para que el ciclo se interrumpa
}
else {
    echo '<p>Error al cargar el fichero</p>';
}    
    
answered by 12.11.2018 в 17:40