【发布时间】:2010-10-17 18:30:38
【问题描述】:
我想使用 php 读取网页中文件夹中的文件名列表。 有什么简单的脚本可以实现吗?
【问题讨论】:
我想使用 php 读取网页中文件夹中的文件名列表。 有什么简单的脚本可以实现吗?
【问题讨论】:
最简单最有趣的方式(imo)是glob
foreach (glob("*.*") as $filename) {
echo $filename."<br />";
}
但标准方法是使用directory functions.
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: .".$file."<br />";
}
closedir($dh);
}
}
还有SPL DirectoryIterator methods。如果你有兴趣
【讨论】:
$dir = getcwd(); 获取当前工作目录。
!== false的目的是什么?
如果你访问路径有问题,也许你需要把这个:
$root = $_SERVER['DOCUMENT_ROOT'];
$path = "/cv/";
// Open the folder
$dir_handle = @opendir($root . $path) or die("Unable to open $path");
【讨论】:
有一个球。在这个网页上有很好的文章如何以非常简单的方式列出文件:
【讨论】:
有这个函数scandir():
$dir = 'dir';
$files = scandir($dir, 0);
for($i = 2; $i < count($files); $i++)
print $files[$i]."<br>";
【讨论】:
这是我喜欢做的事情:
$files = array_values(array_filter(scandir($path), function($file) use ($path) {
return !is_dir($path . '/' . $file);
}));
foreach($files as $file){
echo $file;
}
【讨论】:
签入多个文件夹:
Folder_1 和 folder_2 是文件夹的名称,我们必须从中选择文件。
$format 是必需的格式。
<?php
$arr = array("folder_1","folder_2");
$format = ".csv";
for($x=0;$x<count($arr);$x++){
$mm = $arr[$x];
foreach (glob("$mm/*$format") as $filename) {
echo "$filename size " . filesize($filename) . "<br>";
}
}
?>
【讨论】:
您可以使用标准目录函数
$dir = opendir('/tmp');
while ($file = readdir($dir)) {
if ($file == '.' || $file == '..') {
continue;
}
echo $file;
}
closedir($dir);
【讨论】:
在RecursiveTreeIterator 类的帮助下,还有一个非常简单的方法可以做到这一点,在这里回答:https://stackoverflow.com/a/37548504/2032235
【讨论】:
<html>
<head>
<title>Names</title>
</head>
<body style="background-color:powderblue;">
<form method='post' action='alex.php'>
<input type='text' name='name'>
<input type='submit' value='name'>
</form>
Enter Name:
<?php
if($_POST)
{
$Name = $_POST['name'];
$count = 0;
$fh=fopen("alex.txt",'a+') or die("failed to create");
while(!feof($fh))
{
$line = chop(fgets($fh));
if($line==$Name && $line!="")
$count=1;
}
if($count==0 && $Name!="")
{
fwrite($fh, "\r\n$Name");
}
else if($count!=0 && $line!="")
{
echo '<font color="red">'.$Name.', the name you entered is already in the list.</font><br><br>';
}
$count=0;
fseek($fh, 0);
while(!feof($fh))
{
$a = chop(fgets($fh));
echo $a.'<br>';
$count++;
}
if($count<=1)
echo '<br>There are no names in the list<br>';
fclose($fh);
}
?>
</body>
</html>
【讨论】: