简体   繁体   English

获取 PHP 文件/图像扩展名

[英]Get Php file/images extension

I'm trying to get a images file extension and add some random number.我正在尝试获取图像文件扩展名并添加一些随机数。 Like 348678423.jpeg, 343344343.jpg, 32434343.gif, 3434343.png etc..348678423.jpeg、343344343.jpg、32434343.gif、3434343.png 等。

So following is my php code:所以以下是我的php代码:

function getExtension($str)
{
     $i = strrpos($str,".");
 if (!$i) { return ""; }
 $l = strlen($str) - $i;
 $ext = substr($str,$i+1,$l);
 return $ext;
}
  @$extension = getExtension($file);
   $extension = strtolower($extension);
  $image_named_uniq = uniqid().'.'.$extension;  

But when i echo this variable $image_named_uniq it's just show the random number, Like: 50aa5a2e0f425.但是当我回显这个变量$image_named_uniq 时,它只是显示随机数,比如: 50aa5a2e0f425。 It's should be show 50aa5a2e0f425.jpg etc..它应该是显示50aa5a2e0f425.jpg等。

What is wrong in my code?我的代码有什么问题?

如果您只需要扩展名:

echo end(explode('.', $str));

You can use pathinfo() to get the extension您可以使用pathinfo()获取扩展名

$path_parts = pathinfo($filename);
echo $path_parts['extension'];

The answer posted by @jereon is correct, and the easiest way to do this. @jereon 发布的答案是正确的,也是最简单的方法。

However, if you would like to extract more information about the file without using explode and end, you can simply use the PHP built in pathinfo() function.但是,如果您想在不使用explode 和end 的情况下提取有关文件的更多信息,则可以简单地使用PHP 内置的pathinfo()函数。

Reference: pathinfo()参考: pathinfo()

<?php
    $path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');

    echo $path_parts['dirname'], "\n";
    echo $path_parts['basename'], "\n";
    echo $path_parts['extension'], "\n";
    echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>

This will return这将返回

/www/htdocs/inc
lib.inc.php
php
lib.inc

As $filename is an array, you need to loop through it in order to read it into pathinfo() .由于$filename是一个数组,您需要遍历它才能将其读入pathinfo() This can be done very easily using a foreach loop like so:这可以很容易地使用 foreach 循环来完成,如下所示:

// Loop through the filenames array
foreach($filename as $value){
    // Retrieve the path parts of each individual file
    $path_parts[] = pathinfo($value);
}

// Write out the path parts array
print_r($path_parts);

The easiest way would be to use pathinfo() .最简单的方法是使用pathinfo() Note that the result is based on the filename and no introspection on the file is performed (eg. the image logo.jpg renamed to logo.php will result in a .php file extension. Use the fileinfo extension if you want to get the filetype by it's contents)请注意,结果基于文件名,并且不会对文件进行自省(例如,图像logo.jpg重命名为logo.php将导致文件扩展名为.php 。如果要获取文件类型,请使用fileinfo 扩展名由它的内容)

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

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