Home Ask Login Register

Developers Planet

Your answer is one click away!

Saif Morshed February 2016

I want to display file list using file type

        //scan "uploads" folder and display them accordingly
       $scan = scandir('uploads');

            foreach($scan as $file)
               if (is_image("uploads/$file"))
                { ?>
                    <p><?php echo "this is an image"; ?></p>
              if (is_pdf("uploads/$file"))
                { ?>
                    <p><?php echo "this is an PDF file"; ?></p>
              if (is_html("uploads/$file"))
                { ?>
                    <p><?php echo "this is an HTML file"; ?></p>


I want to display the file as file type. If the file is an image show this is an image, if the file is PDF show the file is PDF Please Help me with this code. Pls, Pls


Landen February 2016

You can do a simple str_pos() / substr() to detect if the string contains a .pdf file extension or a .html or a .png/.jpg.

Here's some example code:

if (substr($filename, -4) == '.jpg') {
       echo "Jpeg!";

Just make the other switches for the different file types and you're golden. Ideally, pass all the files to one function and have all the logic contained there.

AbraCadaver February 2016

You don't have to rely on the file extension:

$fi = finfo_open(FILEINFO_MIME_TYPE);

foreach(scandir('uploads') as $file) {
    echo finfo_file($fi, $file);

Or to get the extension:

echo pathinfo($file, PATHINFO_EXTENSION);

CodeGodie February 2016

I would use DirectoryIterator and its methods like this:

$scan = "uploads";
$dir = new DirectoryIterator($scan);
foreach ($dir as $file) {
    if (!$file->isDot()) {
        $ext = $file->getExtension();
        switch ($ext) {
            case "img":
            case "png":
            case "gif":
                $text = "This is an image";
            case "html":
                $text = "This is HTML";
            case "pdf":
                $text = "This is PDF";
                $text = "";
        echo $text;

Post Status

Asked in February 2016
Viewed 1,315 times
Voted 5
Answered 3 times


Leave an answer

Quote of the day: live life