PHP check file extension

Php

Php Problem Overview


I have an upload script that I need to check the file extension, then run separate functions based on that file extension. Does anybody know what code I should use?

if (FILE EXTENSION == ???)
{
FUNCTION1
}
else if
{
FUNCTION2
}

Php Solutions


Solution 1 - Php

pathinfo is what you're looking for

PHP.net

$file_parts = pathinfo($filename);

switch($file_parts['extension'])
{
    case "jpg":
    break;

    case "exe":
    break;

    case "": // Handle file extension for files ending in '.'
    case NULL: // Handle no file extension
    break;
}

Solution 2 - Php

$info = pathinfo($pathtofile);
if ($info["extension"] == "jpg") { .... }

Solution 3 - Php

For php 5.3+ you can use the SplFileInfo() class

$spl = new SplFileInfo($filename); 
print_r($spl->getExtension()); //gives extension 

Also since you are checking extension for file uploads, I highly recommend using the mime type instead..

For php 5.3+ use the finfo class

$finfo = new finfo(FILEINFO_MIME);
print_r($finfo->buffer(file_get_contents($file name)); 

Solution 4 - Php

$file_parts = pathinfo($filename);

$file_parts['extension'];
$cool_extensions = Array('jpg','png');

if (in_array($file_parts['extension'], $cool_extensions)){
    FUNCTION1
} else {
    FUNCTION2
}

Solution 5 - Php

$path = 'image.jpg';
echo substr(strrchr($path, "."), 1); //jpg

Solution 6 - Php

  $original_str="this . is . to . find";
  echo "<br/> Position: ". $pos=strrpos($original_str, ".");
  $len=strlen($original_str);
  if($pos >= 0)
  {
	echo "<br/> Extension: ".   substr($original_str,$pos+1,$len-$pos) ;
   } 

Solution 7 - Php

$file = $_FILES["file"] ["tmp_name"]; 
$check_ext = strtolower(pathinfo($file,PATHINFO_EXTENSION));
if ($check_ext == "fileext") {
    //code
}
else { 
    //code
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser547794View Question on Stackoverflow
Solution 1 - PhpBrombombView Answer on Stackoverflow
Solution 2 - PhpAlon EitanView Answer on Stackoverflow
Solution 3 - PhpRotimiView Answer on Stackoverflow
Solution 4 - PhpimaginabitView Answer on Stackoverflow
Solution 5 - PhpAiryView Answer on Stackoverflow
Solution 6 - PhpJasmeenView Answer on Stackoverflow
Solution 7 - PhpGeniusGeekView Answer on Stackoverflow