PHP 读取文件夹仅适用于绝对路径

交互的

我有一个函数可以读出包含图像的文件夹。
问题是它仅在文件夹路径是绝对路径时才有效。

如果我将其更改为动态路径,则会引发错误。

这是函数:

<?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;
}
?>

这是我获取它的方式:

<?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].'">';
    }
}
?>

我怎样才能使它与相对路径一起工作?

巴托斯·扎萨达

我要用一个问题来回答你的问题:为什么它应该使用相对路径?

它不能使用相对路径的最可能原因是,当前工作目录不是您认为的那样。你可以用getcwd()函数检查它

这也是相对路径的最大问题:你永远不能依赖它们。可以chdir()随时出于任何原因从脚本外部设置当前工作目录

每当您处理服务器上的文件时,始终使用绝对路径。如果要解析相对于脚本文件的路径,请始终使用__DIR__dirname()

在您的情况下,您的代码的问题在于您的getPathsByKind函数返回图像的绝对路径,这对除 localhost 之外的任何人都没用。您可以做的是getPathsByKind仅返回文件名而不是完整路径。替换线

$file[] =   $filename;

$file[] = pathinfo($filename, PATHINFO_BASENAME);

然后,在img标签添加路径

for($i=0; $i < 32; $i++){
    echo '<img src="/images/logos/or/whatever/'.$files[$i].'">';
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章