无法获取图像文件扩展名 [英] Not able to get image file extension

查看:128
本文介绍了无法获取图像文件扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Uploadify将图像上传到服务器.
图像已上传,并放置在Web服务器的temp文件夹中.

I'm using Uploadify to upload an image to the server.
The image is uploaded, and placed in the temp folder of the web server.

现在,我需要处理文件beore并将其移动到实际位置,并且我有以下代码:

Now I need to work with the file beore moving it to it's real location, and I have the following code:

// Get the filepath and filename from server temp dir
$sourceFile   = $_FILES[ 'Filedata' ][ 'tmp_name' ]; // e.g. c:\server\path\tmp\php159.tmp

// Solution 1 for getting file extension
$fileExt1     = pathinfo($sourceFile, PATHINFO_EXTENSION); // <-- This only returns .tmp

// Solution 2 with getimagesize
list(,,$extension) = getimagesize($sourceFile);
$fileExt2     = $extension; // this only returns the number 2.

// Solution 3 with getimagesize
$img = getimagesize($sourceFile);
$fileExt3 = $img[2]; // this only returns the number 2.

我不使用正则表达式读取文件名,因为用户可以给文件命名任何东西,所以我必须读取文件数据.

I'm not using regex to read filename, because a user may name the file anything, so I have to read file data.

有人建议吗?

推荐答案

好吧,首先$ sourceFile应该是$_FILES['Filedata']['name']而不是$_FILES['Filedata']['tmp_name'],但是仅用于第一个解决方案.

Well, first off $sourceFile should be $_FILES['Filedata']['name'] instead of $_FILES['Filedata']['tmp_name'] but only for your first solution.

现在有关您的解决方案/问题:

Now regarding your solutions/problems:

  1. pathinfo($sourceFile, PATHINFO_EXTENSION);//应该可以正常工作
  2. getimagesize()返回一个常量,该常量指示第二个索引中的图像类型
  3. 与第2点相同
  1. pathinfo($sourceFile, PATHINFO_EXTENSION); // should work now
  2. getimagesize() returns a constant indicating the image type in the second index
  3. same as point 2

请记住,exif_imagetype()返回的信息与getimagesize()的第二个索引完全相同,如果可以使用此功能,它的性能应该会更好.

Keep in mind that exif_imagetype() returns exactly the same information as the second index of getimagesize(), if you have access to this function it should perform way better.

现在,对于图像常量,最常见的三个是:

Now for the image constants, the most common three are:

  • IMAGETYPE_GIF = 1
  • IMAGETYPE_JPEG = 2
  • IMAGETYPE_PNG = 3

检查就像做这样的事情一样简单:

Checking is as simple as doing something like this:

switch (exif_imagetype($_FILES['Filedata']['tmp_name']))
{
    case IMAGETYPE_GIF:
        echo 'is a GIF';
    break;

    case IMAGETYPE_JPEG:
        echo 'is a JPEG';
    break;

    case IMAGETYPE_PNG:
        echo 'is a PNG';
    break;

    case default:
        echo 'is something else;
    break;
}

还有一件事,使用getimagesize()/exif_imagetype()比依靠文件扩展名更好,因为扩展名可以轻松更改.

One more thing, it's better to use getimagesize() / exif_imagetype() than to rely on the file extension, since the extension can be easily changed.

这篇关于无法获取图像文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆