Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

yii

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.

like image 398
Ashish Avatar asked Jan 16 '13 20:01

Ashish


People also ask

What is glob() in php?

The glob() function returns an array of filenames or directories matching a specified pattern. The glob() function returns. An array containing the matched files/directories, Returns an empty array if no file is matched, FALSE on error.

How we can define a filename in PHP?

Method 1: Using basename() function: The basename() function is an inbuilt function that returns the base name of a file if the path of the file is provided as a parameter to the basename() function. Syntax: $filename = basename(path, suffix);

How do I get a list of files in a directory in PHP?

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

What is glob return?

The glob. glob returns the list of files with their full path (unlike os. listdir()) and is more powerful than os. listdir that does not use wildcards.


2 Answers

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); ?> 
like image 66
Asgaroth Avatar answered Sep 21 '22 09:09

Asgaroth


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

like image 28
ernie Avatar answered Sep 19 '22 09:09

ernie