Search files in a folder with PHP


I have a folder with N number of files with different extensions, when I upload the file to the folder I rename it with a number, for example: 1.jpg or 4.docx or 7.pdf. I need you to list the file without knowing what extension it has, that is, when I upload the page by GET method I send the code of the number it has without knowing what extension it has. Ex: localhost / example / index.php? Code = 1 What I need is for the page to go and look for the file folder, the file that is called 1 regardless of the extension it has. Thanks!

asked by Fredy Aristizábal Aristizábal 25.12.2017 в 22:32

1 answer


You can do the following

// Ruta del directorio donde están los archivos
$path  = '/tmp'; 

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

Then you go through the arrangement and you make a simple explode to each element

// 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 $fileName;
        // Realizamos un break para que el ciclo se interrumpa
answered by 25.12.2017 в 22:46