-1

我有一个 PHP 代码,可以在列表中显示目录的文件内容。每个文件都是链接的,因此如果单击,它将下载或打开。目录内的文件将是客户上传的文件。如果文件名包含空格,则链接已损坏且无法打开,因此我希望将空格替换为下划线。

我知道 str_replace 可以满足我的要求,但是我不确定如何将其应用于此代码(我没有编写)。

// Define the full path to your folder from root 
$path = "uploads/artwork"; 


// Open the folder 
$dir_handle = @opendir($path) or die("Unable to open $path"); 

// Loop through the files 
while ($file = readdir($dir_handle)) { 

if($file == "." || $file == ".." || $file == "index.php" ) 

    continue; 
    echo "<a href=uploads/artwork/$file>$file</a><br />"; 

} 
// Close 
closedir($dir_handle); 

非常感谢所有帮助。谢谢!

4

1 回答 1

5

当您将它们保存到服务器时,您还必须用下划线替换文件名。

由于您没有保存文件的位置的代码,因此您可以urlencode()链接 URL,这样它就不会被危险字符破坏。请注意,最初它被空格打破,因为你没有href用引号括起来的值,我在这里做的:

echo "<a href='" . urlencode("uploads/artwork/$file") . "'>$file</a><br />";

否则,要用下划线替换空格,你会这样做:

echo "<a href=" . str_replace( ' ', "_", "uploads/artwork/$file") . ">$file</a><br />";

但同样,这可能需要您在上传时更改文件名。

请注意,您还需要调用该链接htmlentities()$file一部分,以防止诸如<破坏 HTML 页面之类的字符。因此,最终结果将是:

echo "<a href='" . urlencode("uploads/artwork/$file") . "'>" . htmlentities( $file) . "</a><br />";
于 2012-11-07T17:41:05.920 回答