【问题标题】:How do I get a File Extension in PHP if I only have the File Name?如果我只有文件名,如何在 PHP 中获得文件扩展名?
【发布时间】:2015-11-19 17:28:04
【问题描述】:

我有图像文件/files/uploads/1 的路径,但如您所见,我没有扩展名,因此无法显示图像。如何获取文件的扩展名以便显示它?谢谢!

编辑:这是我尝试过的代码。 BMP、PNG、JPG、JPEG 和 GIF 是唯一可能的扩展名,但 $path 最终永远不会被分配一个值。

$exts = array('bmp','png','jpg','jpeg','gif');
foreach ($exts as $ext) {
    if (file_exists("/files/uploads/" . $id . "." . $ext)) {
        $path = "/files/uploads/" . $id . "." . $ext;
    }
}

【问题讨论】:

标签: php image file file-extension


【解决方案1】:

首先,我认为当你得到图像的文件名时,意味着不需要添加扩展名,所以你有文件名和图像文件夹

它应该看起来像这样:

$fullpath = ('uploadword/'.$filename);
// then call it 
<img  src='".$fullpath."'> 

正常情况是上传特定文件夹中的所有图片,然后获取文件名并保存在数据库中

move_uploaded_file($file_tmp,"upload/".$filename);

一些专业人士使文件名唯一化变得更加复杂,因为他们期望一些重复的值和许多原因,这里是一种简单的技术:

$anynameorfunction = "";// random number etc...
$newname = $anynameorfunction.$filename;
move_uploaded_file($file_tmp,"upload/".$newname);

所以,当他们再次调用它时,它应该像这样简单

  $fullpath = ('uploadword/'.$newname);
 // then call it 
  <img  src='".$newname."'> 

这是一种非常简单的方式,我希望你明白我的意思

【讨论】:

    【解决方案2】:

    显示图像不需要文件扩展名。

    <img src="/files/uploads/1">
    

    将显示图像。 placehold.it 图像的工作方式与此相同

    <img src="http://placehold.it/350x150">
    

    【讨论】:

    • 这是我的程序最初做的,但它没有工作。这就是为什么我首先要寻找一种获得扩展的方法。
    【解决方案3】:

    就我个人而言,我遇到了一个问题,即在 file_exists 检查中的路径前有一个不必要的斜杠 (/),但问题的解决方案仍然相同。

    $exts = array('bmp','png','jpg','jpeg','gif','swf','psd','tiff','jpc','jp2','jpx','jb2','swc','iff','wbmp','xbm','ico');
    foreach ($exts as $ext) {
        if (file_exists("files/uploads/" . $id . "." . $ext)) {
            $path = "/files/uploads/" . $id . "." . $ext;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      • 1970-01-01
      • 2012-05-09
      相关资源
      最近更新 更多