PHP - List the files of a sub-directory

December 2016



Issue


I've currently created a small site that can scan a folder and list all the video files present in the later.

I can not get it to scan the subfolder of my root folder and add these files to my database.
Here is my code:

<?php 
include_once 'function.inc.php'; 
$dsn = "mysql:host=localhost;dbname=dvix"; 
$user = "root"; 
$password = ""; 

try { 
    $db = new PDO($dsn, $user, $password); 
} catch (PDOException $e) { 
    die("Erreur !:" . $e->getMessage()); 
} 

$prepareStatement = $db->query("SELECT n_file FROM t_film "); 
$connect = $prepareStatement->fetchAll(); 
$rep = "F:\DVD"; 
$dir = opendir($rep); 

while ($file = readdir($dir)) { 
     
    if (($file != ".") && ($file != "..")) { 
        $info = pathinfo($file); 
        $found = false; 
        foreach ($connect as $value) { 
             
            if ($value['n_file'] == $file) { 
                $found = true; 
                break; 
            } 
        } 
        if ($found == false) { 
            $statement = "INSERT INTO t_film  
            (n_file,n_title,n_synopsis,n_ctg,n_date) 
            VALUES ('$file','".$info['filename']."','','".$info['extension']."',' ')"; 
            $db->exec($statement); 
        } 
    } 
} 

header('Location: index.php'); 
?> 

Solution


Try this:

function scan($rep) { 
global $db; 
$dir = opendir($rep); 
while ($file = readdir($dir)) { 
     
    if (($file != ".") && ($file != "..")) { 
        if (is_dir($rep.$file))  {  
        scan($file); 
        } else { 
        $info = pathinfo($file); 
        $found = false; 
        foreach ($connect as $value) { 
             
            if ($value['n_file'] == $file) { 
                $found = true; 
                break; 
            } 
        } 
        if ($found == false) { 
            $statement = "INSERT INTO t_film  
            (n_file,n_title,n_synopsis,n_ctg,n_date) 
            VALUES ('$file','".$info['filename']."','','".$info['extension']."',' ')"; 
            $db->exec($statement); 
        } 
    } 
    } 
} 
} 
scan("F:\DVD");



Thanks to neoprog67 for this tip.

Related :

This document entitled « PHP - List the files of a sub-directory » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.