我写了一个简短的PHP代码,它显示了目录中每个文件的图像和标题。问题是,如果我运行代码,许多文件将获得a而不是图像。因此,例如.zip文件位于.txt文件的前面。现在它将显示txt文件而不是.zip图像。
代码:
$file_dir = "upload/demofiles";
if ($handle = opendir($file_dir)) {
$i = 1;
while (false !== ($entry = readdir($handle))) {
$format = pathinfo($entry, PATHINFO_EXTENSION);
$file_path = $file_dir.'/'.$entry;
if($format == "txt"){
$myfile = fopen($file_path, "r") or die("Unable to open file!");
$file_element = '<iframe src="'.$file_path.'" width="80px" style="height:80px" scrolling="no"></iframe>';
}
if($format == "png"){
$myfile = fopen($file_path, "r") or die("Unable to open file!");
$file_element = '<img src="'.$file_path.'" />';
}
if($format == "zip"){
$myfile = fopen($file_path, "r") or die("Unable to open file!");
$file_element = '<img width="64px" class="img" src="icons/zip.png" />';
fclose($myfile);
}
if($format == "pdf"){
$file_element = '<embed src="'.$file_path.'" width="80px" scrolling="no" style="height:80px">';
}
if(!isset($file_element)){
$file_element = '<img class="img" width="64px" src="icons/file.png">';
}
if ($entry != "." && $entry != "..") {
echo '<label style="display:inline-block; border:solid 1px;">
<div>'.$file_element.'</div>
<div>'.$entry.'</div>
</label>';
}
$i++;
}
}
为什么会这样?我认为应该在循环运行后清除变量。
谢谢!
答案 0 :(得分:0)
试试这段代码:
$file_dir = "upload/demofiles";
if ($handle = opendir($file_dir)) {
$i = 1;
while (false !== ($entry = readdir($handle))) {
$format = pathinfo($entry, PATHINFO_EXTENSION);
$file_path = $file_dir.'/'.$entry;
switch($format){
case "txt":
$myfile = fopen($file_path, "r") or die("Unable to open file!");
$file_element = '<iframe src="'.$file_path.'" width="80px" style="height:80px" scrolling="no"></iframe>';
break;
case "png":
$myfile = fopen($file_path, "r") or die("Unable to open file!");
$file_element = '<img src="'.$file_path.'" />';
break;
case "zip":
$myfile = fopen($file_path, "r") or die("Unable to open file!");
$file_element = '<img width="64px" class="img" src="icons/zip.png" />';
fclose($myfile);
break;
case "pdf":
$file_element = '<embed src="'.$file_path.'" width="80px" scrolling="no" style="height:80px">';
break;
default:
$file_element = '<img class="img" width="64px" src="icons/file.png">';
break;
}
if ($entry != "." && $entry != "..") {
echo '<label style="display:inline-block; border:solid 1px;">
<div>'.$file_element.'</div>
<div>'.$entry.'</div>
</label>';
}
$i++;
}
}