Handsome Handsome - 1 year ago 61
PHP Question

Match string to a filename from folder using php

Hi I wonder if it is possible to match a string to a file from folder using php.

For example I have a folder called uploads and inside, I have different files like image1.png, image2.jpg, doc1.doc, and doc2.pdf.

Assuming I have this code on my php file:

$string = "image2";

// I need some function to display the image2 on my webpage.
// If string "image2" is found in the uploads folder
// then it should display the image



Answer Source

I think this one should do what you want

$dir = "uploads";//the path to your folder
  if ($dh = opendir($dir)) {
              while (($file = readdir($dh)) !== false) {
                  if (!is_dir($file)) {

                    if ($file == "image2"){
                        // your code
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download