0
Thanks

A few words of thanks would be greatly appreciated.

PHP - List the files of a sub-directory



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.
0
Thanks

A few words of thanks would be greatly appreciated.

Ask a question
CCM is a leading international tech website. Our content is written in collaboration with IT experts, under the direction of Jean-François Pillou, founder of CCM.net. CCM reaches more than 50 million unique visitors per month and is available in 11 languages.
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).

Subscribe To Our Newsletter!

The Best of CCM in Your Inbox

Subscribe To Our Newsletter!