Jump to content

List all items in a directory of a certain filetype


DaveLinger

Recommended Posts

How can I list all of the, say, mp3 and wav files in a directory and display some of their stats? I'd like something like this as a result:

 

///

 

3 items found

 

"A song about soccer" - 1.85MB mp3

"Basketball is cool" - 2.10MB wav

"Cool song" - 1.11MB mp3

 

///

 

I understand that the filesize will probably be in bytes, but that's not a big deal and isn't really important right now. I'd also like to know if it's possible to read any metadata from the files, like creation date, modified date, etc.

$dirpath = $_SERVER['DOCUMENT_ROOT']."/somefolder/";

$dir = opendir($dirpath);

while (($filename = readdir($dir)) !== false) {

    $mimetype = mime_content_type($filename);  //Mime Type

    if ($mimetype == "audio/mpeg3" OR $mimetype == "audio/wav") {

          echo $filename." ";  //Filename

          echo filesize($dirpath.$filename)." ";  //Filesize

          echo $mimetype;

    }

}

 

 

Thanks for your help, fanfavorite. Correct me if I'm wrong, but this code does not read or use the actual filename extension at all, right? It actually uses the mimetype - and wouldn't that mean that it would echo, for example, "audio/mpeg3" instead of "mp3"?

When you upload a file (let's say to $_FILES['myfile']) you can use $_FILES['myfile']['type'] to determine the type of the file.

 

You can always run a switch() statement against $_FILES['myfile']['type'] to count them with the default counting unknown files.

You can try something like this:

 

$allowed_files = array("mp3","wav");

$path = "./dir/";
$dir = opendir("./dir/");
while(($file = readdir($dir)) !== false){
//Begin the loop.

if(filetype($path.$file) == "file"){
	//Check to make sure it's not a directory.

	if(in_array(substr($file,strrpos($file,".") + 1), $allowed_files)){
		//Check to make sure it's a valid file.

		$size = round(filesize($path.$file) / 1024,2);
		$ext = substr($file, strrpos($file,".") + 1);

		echo $file . " " . $size . "MB " . $ext . "<br />";
	}
}
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.