本文实例讲述了php模拟服务器实现autoindex效果的方法。分享给大家供大家参考。具体实现方法如下:
1.PHP代码如下:
复制代码 代码如下:
<?php
//文件浏览程序
error_reporting(0);
$pwd = empty($_GET['dir']) ? './' : $_GET['dir'];
$pwd = realpath($pwd);
if(is_file($pwd)) {
highlight_file ($pwd);
exit;
}else
$it = new FilesystemIterator($pwd);
?>
<html>
<head>
<title>pwd of <?php echo $pwd ?></title>
</head>
<body bgcolor="white">
<h1>pwd of <?php echo $pwd ?></h1><hr>
<pre><a href="?dir=<?php echo dirname($pwd)?>">../</a>
<?php
foreach ($it as $file){
if($file->isDir()) {
$fileSize = '_';
$fileName = $file->getFilename() . '/';
} elseif($file->isFile()) {
$fileSize = $file->getSize();
$fileName = $file->getFilename();
}
$date = date('Y-m-d H:i',$file->getCTime());
?><a href="?dir=<?php echo $file->getRealPath()?>"><?php echo $fileName ?></a><?php echo str_pad($date, 60-strlen($fileName),' ',STR_PAD_LEFT)?><?php echo str_pad($fileSize,30,' ',STR_PAD_LEFT)?>
<?php }?></pre><hr>
</body>
</html>
//文件浏览程序
error_reporting(0);
$pwd = empty($_GET['dir']) ? './' : $_GET['dir'];
$pwd = realpath($pwd);
if(is_file($pwd)) {
highlight_file ($pwd);
exit;
}else
$it = new FilesystemIterator($pwd);
?>
<html>
<head>
<title>pwd of <?php echo $pwd ?></title>
</head>
<body bgcolor="white">
<h1>pwd of <?php echo $pwd ?></h1><hr>
<pre><a href="?dir=<?php echo dirname($pwd)?>">../</a>
<?php
foreach ($it as $file){
if($file->isDir()) {
$fileSize = '_';
$fileName = $file->getFilename() . '/';
} elseif($file->isFile()) {
$fileSize = $file->getSize();
$fileName = $file->getFilename();
}
$date = date('Y-m-d H:i',$file->getCTime());
?><a href="?dir=<?php echo $file->getRealPath()?>"><?php echo $fileName ?></a><?php echo str_pad($date, 60-strlen($fileName),' ',STR_PAD_LEFT)?><?php echo str_pad($fileSize,30,' ',STR_PAD_LEFT)?>
<?php }?></pre><hr>
</body>
</html>
2. 运行效果如下图所示:
希望本文所述对大家的php程序设计有所帮助。