PHP - List the files of a sub-directory

October 2017



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.
Published by aakai1056. Latest update on December 9, 2011 at 10:13 AM by aakai1056.
This document, titled "PHP - List the files of a sub-directory," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (ccm.net).