PHP:列出目录中的类型文件并链接到它们

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8956701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 05:50:42  来源:igfitidea点击:

PHP : List Files of Type in Directory and Link to them

php

提问by e__

I've got the code

我有代码

$directory = "C:/My file path";
$phpfiles = glob($directory . "*.html");

foreach($phpfiles as $phpfiles)
{
echo $phpfiles;
}

But how would I change it so that it doesn't just list the files, but actually links to them?

但是我将如何更改它以便它不仅列出文件,而且实际上链接到它们?

回答by Eray

First of all, don't use same variable names at foreach(). You can link to files, like this.

首先,不要在 foreach() 中使用相同的变量名。您可以像这样链接到文件。

foreach($phpfiles as $phpfile)
{
echo "<a href=$phpfile>".basename($phpfile)."</a>";
}

$phpfilecontaining full path of file (for example : /home/eray/Desktop/test.html)

$phpfile包含文件的完整路径(例如:/home/eray/Desktop/test.html)

basename()is returning just file name from path . basename($phpfile)'s output is test.html. If you want to print just test(without .htmlextension) , you can use this : basename($phpfile, ".html")Thanks, @aSeptik.

basename()只从 path 返回文件名。basename($phpfile)的输出是test.html。如果您只想打印test(没有.html扩展名),您可以使用这个:basename($phpfile, ".html")谢谢,@aSeptik。

回答by davidethell

Assuming that the links are accessible via a web server you'll need a different root path for web access than you have on your computer. Also, your foreach is wrong. The second variable needs to be singular (well, at least different than the first). So assuming your web server sees the file path as a valid site path:

假设可以通过网络服务器访问这些链接,您需要一个与计算机上不同的根路径来访问网络。另外,你的 foreach 是错误的。第二个变量需要是单数(好吧,至少与第一个不同)。因此,假设您的 Web 服务器将文件路径视为有效的站点路径:

$rootPath = "/MyFilePath";
foreach ($phpfiles as $phpfile)
{
    echo "<a href=\"$rootPath/$phpfile\">$phpfile</a>";
}

回答by Luca Filosofi

$files = glob("*.html");
echo '<ul>'.implode('', array_map('sprintf', array_fill(0, count($files), '<li><a href="%s">%s</a></li>'), $files, $files)).'</ul>';

回答by user2988099

This is ok "eray"

这是好的“eray”

$phpfile containing full path of file (for example : /home/eray/Desktop/test.html) basename() is returning just file name from path . basename($phpfile)'s output is test.html . If you want to print just test (without .html extension) , you can use this : basename($phpfile, ".html") Thanks, @aSeptik.

$phpfile 包含文件的完整路径(例如:/home/eray/Desktop/test.html) basename() 仅从 path 返回文件名。basename($phpfile) 的输出是 test.html 。如果你只想打印测试(没有 .html 扩展名),你可以使用这个: basename($phpfile, ".html") 谢谢,@aSeptik。

how to remove. php extension and in the link.

如何去除。php 扩展名并在链接中。

exaple: http//example.com/dir1/file.php **

例如: http//example.com/dir1/file.php **

(with out .php on end).

(没有 .php 结束)。



Thanks

谢谢