Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop through the files in a folder in php

Tags:

php

i have searched through the Internet and found the scrip to do this but am having some problems to read the file names.

here is the code

$dir = "folder/*";
 foreach(glob($dir) as $file)  
 {  
 echo $file.'</br>';  
}

this display in this format

folder/s0101.htm
folder/s0692.htm

for some reasons i want to get them in this form.

s0101.htm
s0692.htm

can anyone tell me how to do this?

like image 646
dxcoder1 Avatar asked Mar 18 '14 12:03

dxcoder1


People also ask

How do I see all PHP files in a specific folder?

PHP using scandir() to find folders in a directory The scandir function is an inbuilt function that returns an array of files and directories of a specific directory. It lists the files and directories present inside the path specified by the user.

What does Scandir return?

Definition and Usage The scandir() function returns an array of files and directories of the specified directory.


2 Answers

Just use basename() wrapped around the $file variable.

<?php
$dir = "folder/*";
foreach(glob($dir) as $file)
{
    if(!is_dir($file)) { echo basename($file)."\n";}
}

The above code ignores the directories and only gets you the filenames.

like image 134
Shankar Narayana Damodaran Avatar answered Sep 19 '22 00:09

Shankar Narayana Damodaran


You can use pathinfo function to get file name from dir path

$dir = "folder/*";
 foreach(glob($dir) as $file) {  
  $pathinfo = pathinfo($file);
  echo $pathinfo['filename']; // as well as other data in array print_r($pathinfo);
}
like image 45
Girish Avatar answered Sep 19 '22 00:09

Girish