简体   繁体   English

如果我只有文件名,如何在PHP中获得文件扩展名?

[英]How do I get a File Extension in PHP if I only have the File Name?

I have the path to an image file /files/uploads/1 but as you can see, I don't have an extension so I can't display the image. 我具有图像文件/files/uploads/1的路径,但是如您所见,我没有扩展名,因此无法显示图像。 How can I get the extension of the file so I can display it? 如何获取文件扩展名以便显示? Thanks! 谢谢!

EDIT: Here is come code I have tried. 编辑:这是我尝试过的代码。 BMP, PNG, JPG, JPEG and GIF are the only possible extensions, but $path ends up never getting assigned a value. 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;
    }
}

Personally, I had a problem where I had an unnecessary slash (/) before my path in the file_exists check, but the solution to the question is still the same. 就个人而言,我遇到了一个问题,即在我的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;
    }
}

You don't need a file extension to show an image. 您不需要文件扩展名即可显示图像。

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

Will show the image. 将显示图像。 It's the same way the placehold.it images work 这与placehold.it图片的工作方式相同

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

First of all , I think when you get the file name for the image that means no need to add extension , so you have the file name and image folder 首先,我认为当您获得图像的文件名时,这意味着无需添加扩展名,因此您具有文件名和图像文件夹

it should simply look like this : 它应该看起来像这样:

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

The normal scenario to upload all the images in specific folder then get the filename and save it in data base 正常情况下,将所有图像上传到特定文件夹中,然后获取文件名并将其保存在数据库中

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

Some professional make it more sophisticated to make filename unique ,because they expected some duplicated values and many reasons , here is one simple technique : 一些专业人士使使文件名唯一变得更加复杂,因为他们期望某些重复的值和许多原因,这是一种简单的技术:

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

So, when they call it again it should be simple like this 所以,当他们再次调用它时,应该很简单

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

This is in very simple way and i wish you get what i mean 这很简单,我希望你明白我的意思。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM