I have a function that reads out a folder containing images.
The problem is that it only works if the path to the folder is absolute.
If I change it to a dynamic path it throws me an error.
Here is the function:
<?php
function getPathsByKind($path,$ext,$err_type = false)
{
# Assign the error type, default is fatal error
if($err_type === false)
$err_type = E_USER_ERROR;
# Check if the path is valid
if(!is_dir($path)) {
# Throw fatal error if folder doesn't exist
trigger_error('Folder does not exist. No file paths can be returned.',$err_type);
# Return false incase user error is just notice...
return false;
}
# Set a storage array
$file = array();
# Get path list of files
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path,RecursiveDirectoryIterator::SKIP_DOTS)
);
# Loop and assign paths
foreach($it as $filename => $val) {
if(strtolower(pathinfo($filename,PATHINFO_EXTENSION)) == strtolower($ext)) {
$file[] = $filename;
}
}
# Return the path list
return $file;
}
?>
and here is how I fetch it:
<?php
# Assign directory path
//$directory = '/Applications/MAMP/htdocs/domainname/wp-content/themes/themename/images/logos/';
// THIS PART ABOVE IS THE ABSOLUTE PATH AND IS WORKING.
$directory = get_bloginfo('template_directory').'/images/logos/';
$files = getPathsByKind($directory,'svg');
if(!empty($files)) {
for($i=0; $i < 32; $i++){
echo '<img src="'.$files[$i].'">';
}
}
?>
How can I make it work with a relative path?
I'm gonna answer your question with a question: why should it work with a relative path?
The most likely reason why it doesn't work with a relative path is, the current working directory is not what you think it is. You can check it with getcwd()
function.
This is also the biggest problem with relative paths: you can NEVER rely on them. Current working directory can be set from outside the script with chdir()
any time for any reason.
Whenever you work with files on your server, ALWAYS use absolute paths. If you want to resolve a path relative to the script file, ALWAYS use __DIR__
or dirname()
.
In your case, the problem with your code is that your getPathsByKind
function returns absolute paths to the images, which are useless for anyone except localhost. What you can do is make getPathsByKind
return just file names instead of full paths. Replace line
$file[] = $filename;
with
$file[] = pathinfo($filename, PATHINFO_BASENAME);
then, prepend the path in img
tag:
for($i=0; $i < 32; $i++){
echo '<img src="/images/logos/or/whatever/'.$files[$i].'">';
}