PHP - List the files of a sub-directory

Ask a question


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.
Jean-François Pillou

CCM is a leading international tech website. Our content is written in collaboration with IT experts, under the direction of Jeff Pillou, founder of CCM.net. CCM reaches more than 50 million unique visitors per month and is available in 11 languages.

Learn more about the CCM team