How to return just file name using glob() in php

Posted on

How to return just file name using glob() in php – Here in this article, we will share some of the most common and frequently asked about PHP problem in programming with detailed answers and code samples. There’s nothing quite so frustrating as being faced with PHP errors and being unable to figure out what is preventing your website from functioning as it should like php and yii . If you have an existing PHP-based website or application that is experiencing performance issues, let’s get thinking about How to return just file name using glob() in php.

How can I just return the file name. $image is printing absolute path name?

<?php
$directory = Yii::getPathOfAlias('webroot').'/uploads/';
$images = glob($directory . "*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE);
 foreach($images as $image)
   echo $image
?>

All I want is the file name in the specific directory not the absolute name.

Solution :

Use php’s basename

Returns trailing name component of path

<?php
$directory = Yii::getPathOfAlias('webroot').'/uploads/';
$images = glob($directory . "*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE);
 foreach($images as $image)
   echo basename($image);
?>

Instead of basename, you could chdir before you glob, so the results do not contain the path, e.g.:

<?php
$directory = Yii::getPathOfAlias('webroot').'/uploads/';
chdir($directory); // probably add some error handling around this
$images = glob("*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE);
 foreach($images as $image)
   echo $image;
?>

This is probably a little faster, but won’t make any significant difference unless you have tons of files

One-liner:

$images = array_map('basename', glob($directory . "*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE));

Use basename()

echo basename($image);

You can also remove the extension like this:

echo basename($image, '.php');

Take a look at pathinfo

http://php.net/manual/en/function.pathinfo.php

Pretty helpful function

Example extracting only file names and converting in new array of filenames width extension.

$dir =  get_stylesheet_directory();//some dir - example of getting full path dir in wordpress
$filesPath = array_filter(glob($dir . '/images/*.*'), 'is_file');

$files = array();       
foreach ($filesPath as $file) 
{
   array_push($files, basename($file));
}

If you’re nervous about the unintended consequences of changing the working directory, you can store the current dir with getcwd() before changing, then simply use that value to switch back after you’ve done everything you need to do in that dir.

  <?php
  $directory = Yii::getPathOfAlias('webroot').'/uploads/';
  $working_dir = getcwd();
  chdir($directory);
  $files = glob("*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE);
  chdir($working_dir);
  ?>