62

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
}
user547794
  • 14,263
  • 36
  • 103
  • 152

7 Answers7

127

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;
}
Brombomb
  • 6,988
  • 4
  • 38
  • 57
25
$info = pathinfo($pathtofile);
if ($info["extension"] == "jpg") { .... }
Alon Eitan
  • 11,997
  • 8
  • 49
  • 58
  • I've used this code on a section of my website. However, when executing it along with `echo "$info"` it always returns the value Array. Why is this? – M Smith Apr 29 '16 at 10:39
  • @user2910074 This question is OLD, and I'll have you see your code in order to provide with any help. I suggest that you'll post a question here on SO – Alon Eitan Apr 30 '16 at 20:05
8

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)); 
Rotimi
  • 4,783
  • 4
  • 18
  • 27
7
$file_parts = pathinfo($filename);

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

if (in_array($file_parts['extension'], $cool_extensions)){
    FUNCTION1
} else {
    FUNCTION2
}
Miki
  • 40,887
  • 13
  • 123
  • 202
imaginabit
  • 409
  • 4
  • 9
3
$path = 'image.jpg';
echo substr(strrchr($path, "."), 1); //jpg
Airy
  • 5,484
  • 7
  • 53
  • 78
1
  $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) ;
   } 
Jasmeen
  • 876
  • 9
  • 16
1
$file = $_FILES["file"] ["tmp_name"]; 
$check_ext = strtolower(pathinfo($file,PATHINFO_EXTENSION));
if ($check_ext == "fileext") {
    //code
}
else { 
    //code
}
D. Schreier
  • 1,700
  • 1
  • 22
  • 34
GeniusGeek
  • 315
  • 6
  • 14