Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to get a file extension

Short answer

pathinfo() with the PATHINFO_EXTENSION flag returns the extension:

<?php
 
echo pathinfo('photo.final.JPG', PATHINFO_EXTENSION);

Output:

JPG

For comparing

Lowercase the extension:

<?php
 
$extension = strtolower(pathinfo('photo.final.JPG', PATHINFO_EXTENSION));
 
var_dump(in_array($extension, ['jpg', 'png', 'webp'], true));

Output:

bool(true)

The name without the extension

The PATHINFO_FILENAME flag:

<?php
 
echo pathinfo('/uploads/photo.final.jpg', PATHINFO_FILENAME);

Output:

photo.final

Functions used in this recipe

  • pathinfo — Splits a path into parts: the folder, the name and the extension.
  • basename — Returns the last part of a path — the file name.
  • strtolower — Converts ASCII letters to lowercase.

Thanks for reading!

Donate to the site — we work hard for you.