You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

含&字符的文件夹无法通过DirectoryIterator访问(IIS+Windows Server 2022)

包含&字符的网络文件夹无法通过IIS+PHP访问的问题解决

运行环境为Windows Server 2022搭配IIS,正常情况下可访问不同网络文件夹中的图片,但当文件夹名称包含&字符时,URL会在&处截断,导致系统找不到目标文件夹,无法查看内容。

原PHP代码

<?php 

$selectedDir = isset($_GET["dir"]) ? $_GET["dir"] : "";
//echo $selectedDir;
echo '<h1> '.$selectedDir.' </h1>';
$dirs = "\\server\images\\moreimages/$selectedDir";


$dir = new DirectoryIterator($dirs);
foreach ($dir as $fileinfo) {
    if ($fileinfo->isDir() && !$fileinfo->isDot()) {
        $directorypath = $selectedDir."/".$fileinfo->getFilename();
        echo "<a href='?dir=".$directorypath."'>".$fileinfo->getFilename()."</a><br><br>";
        
    }
    elseif (stripos($fileinfo, '.jpg') !== false || stripos($fileinfo, '.png') !== false) {
        ?>
        <?php  echo '<a target="_blank" href="'.\Intraimages\VD_images/$selectedDir/".$fileinfo.'"/;; ?>
        <?php echo '<img src="'.\Intraimages\VD_images/$selectedDir/".$fileinfo.'"/> </a>;; ?>
        <?php 
    }
}
?>

(说明:\\server\images\moreimages/是UNC路径,\Intraimages\VD_images/是IIS中的虚拟目录路径)

问题详情

  • 问题文件夹名称:35144 MAN T&B T2-L62
  • PHP错误日志:
PHP Fatal error:  Uncaught UnexpectedValueException: DirectoryIterator::__construct(\server\images\moreimages//35000-35999/35144 MAN T): The system cannot find the file specifi (code: 2) in C:\inetpub\wwwroot\Intraimages\index.php:38
  • 对$selectedDir执行var_dump结果:
string(28) "%2F35000-35999%2F35144+MAN+T"
  • 浏览器中的URL:.../?dir=/35000-35999/35144 MAN T&B T2-L62

尝试过的无效解决方法

  • 对$selectedDir使用urlencode
  • 修改php.ini参数:arg_separator.output = "&"、arg_separator.input = ";&"
  • 使用str_replace("&","%26",$selectedDir),但因URL已截断,$selectedDir中无&字符,替换无效

最终解决代码

将遍历目录生成链接的代码替换为:

if ($fileinfo->isDir() && !$fileinfo->isDot()) {
    $directorypath = http_build_query(array($selectedDir."/".$fileinfo->getFilename()));
    $url = parse_url($directorypath);
    $newurl = str_replace('0=','',$url['path']);
    echo "<a href='?dir=".$newurl."'>".$fileinfo->getFilename()."</a><br><br>";        
}

(注:此方案并非最优,因用到了str_replace,但验证了http_build_query可解决URL截断问题)

修改后的URL为:.../?dir=%2F35000-35999%2F35144+MAN+T%26B+T2-L62


内容的提问来源于stack exchange,提问作者Gummi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 11:27:41