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.
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.
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);
The scandir() function returns an array of files and directories of the specified directory.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With