I'm trying to view images in different network folders. Everything works but as soon there's a folder have "&" in its name, I can't view the content. The URL stops after "&" so it can't find the folder in question.
I've looked at other questions similar to this problem but none of them worked (where also many could use strreplace() for a single URL which in my case don't work when I have hundreds of folders)
Running on Windows Server 2022 with IIS.
My code:
<?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
}
}
?>
(For clarification the different paths if it's any help: "\\server\images\moreimages/" is the UNC path. "\Intraimages\VD_images/" is the Virtual Directory path in IIS.)
I will try to provide as much info as I can in advance.
The folder name is: 35144 MAN T&B T2-L62
PHP_errors log:
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
Tried var_dump $selectedDir
which says:
string(28) "%2F35000-35999%2F35144+MAN+T"
URL in my web browser says: .../?dir=/35000-35999/35144 MAN T&B T2-L62
What I've tried
urlencode
the $selectedDir
Change some settings in php.ini to %26:
arg_separator.output = "&"
arg_separator.input = ";&"
Do I need to insert "%26" in the URL instead of "&"? If so, I have no idea how.
EDIT
I tried with:
str_replace("&","%26",$selectedDir);
but the URL and $selectedDir
don't contain "&" since it stops right before "&" so I guess there's nothing to replace...?
SOLVED, this is my new code thanks to the all the help:
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>";
}
NOTE: that this my not be the best solution since i'm using str_replace()
but it just proves that it works with http_build_query
For those who are interested, the new URL is now:
.../?dir=%2F35000-35999%2F35144+MAN+T%26B+T2-L62