Reading file names

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Reading file names

Post by aceconcepts »

Hi,

I have a directory full of images and I need to extract each file name and insert them into a db table.

Does anyone know of a way to read a directory of files and extract file names?
User avatar
seppo0010
Forum Commoner
Posts: 47
Joined: Wed Oct 24, 2007 4:13 pm
Location: Buenos Aires, Argentina

Post by seppo0010 »

Code: Select all

$path = './';
$dir = opendir($path);
while ($file = readdir($dir)) {
	if ($file === '.' || $file === '..' || !is_file($file)) continue;
	echo pathinfo($file, PATHINFO_BASENAME) , "\n";
}
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Post by aceconcepts »

I was able to use this piece of code and it works perfectly.

Code: Select all

$image_file_path = '/home/dp/public_html/dev/velvet/images/products/thumbs/';
if ($handle = opendir($image_file_path)) {
    #echo "Directory handle: $handle\n";
   # echo "Files:\n";

    /* This is the correct way to loop over the directory. */
    while (false !== ($file = readdir($handle)))
	{
       	echo "$file\n<br />";
    }

    /* This is the WRONG way to loop over the directory. */
    /*while ($file = readdir($handle)) {
        echo "$file\n";
    }*/

    closedir($handle);
}
Thanks for the responses.
Post Reply