我要显示目录的内容,并将其超链接插入下拉列表中。这是我的代码。
<select>
<?php
$dir = "/";
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
$target = dirname($_SERVER['PHP_SELF']);
$target=$target.$file;
?>
<option value="<?php $target ?>"><?php $file ?></option>
<?php
}
closedir($dh);
}
}
?>
</select>
我所得到的只是一个空白列表。
这不会输出值:
<?php $target ?>
您需要echo
它或使用=
速记。例如:
<option value="<?php echo $target; ?>"><?php echo $file; ?></option>
或:
<option value="<?= $target ?>"><?= $file ?></option>
我建议您使用类来包装逻辑。 :-)
declare(strict_types=1);
final class Finder
{
/** @var string */
private $path;
public function __construct(string $path){
$this->path = $path;
}
public function folderNames(): array
{
if (!is_dir($this->path)) {
throw new \Exception('Path is not a directory');
}
if (!$directory = opendir($this->path)) {
throw new \Exception('Directory not openable');
}
$directories = [];
while (($file = readdir($directory))) {
if (is_dir($file)) {
$directories[] = $file;
}
}
return $directories;
}
}
// Usage
$dropdown = new Finder(__DIR__);
$directories = $dropdown->folderNames();
echo '<select>';
foreach ($directories as $directory) {
echo "<option value=\"$directory\">$directory</option>";
}
echo '</select>';