<?php
//scan "uploads" folder and display them accordingly
$scan = scandir('uploads');
foreach($scan as $file)
{
if (is_image("uploads/$file"))
{ ?>
<p><?php echo "this is an image"; ?></p>
<?php
}
if (is_pdf("uploads/$file"))
{ ?>
<p><?php echo "this is an PDF file"; ?></p>
<?php
}
if (is_html("uploads/$file"))
{ ?>
<p><?php echo "this is an HTML file"; ?></p>
<?php
}
}
?>
我想将文件显示为文件类型。如果文件是图像显示这是图像,如果文件是PDF,则显示该文件是PDF 请帮我这个代码。请,请
答案 0 :(得分:0)
我会使用DirectoryIterator
及其方法:
$scan = "uploads";
$dir = new DirectoryIterator($scan);
foreach ($dir as $file) {
if (!$file->isDot()) {
$ext = $file->getExtension();
switch ($ext) {
case "img":
case "png":
case "gif":
$text = "This is an image";
break;
case "html":
$text = "This is HTML";
break;
case "pdf":
$text = "This is PDF";
break;
default:
$text = "";
}
echo $text;
}
}
答案 1 :(得分:-1)
您可以执行简单的str_pos()
/ substr()
来检测字符串是否包含.pdf文件扩展名或.html或.png / .jpg。
以下是一些示例代码:
if (substr($filename, -4) == '.jpg') {
echo "Jpeg!";
}
只需为不同的文件类型制作其他开关即可。理想情况下,将所有文件传递给一个函数并包含所有逻辑。
答案 2 :(得分:-1)
您不必依赖文件扩展名:
$fi = finfo_open(FILEINFO_MIME_TYPE);
foreach(scandir('uploads') as $file) {
echo finfo_file($fi, $file);
}
或者获得扩展名:
echo pathinfo($file, PATHINFO_EXTENSION);