PHP Getting the filename and the extension from a string

PHP Getting the filename and the extension from a string

Sometimes when using php you may have a string containing a file location. In many cases (most of the time when you are manipulating images) you may want to create a duplicate or modify the filename in someway. In order to do this you will most likely need to split the filename and the extension into two strings. Then you'll need to rename the file and concatenate the appropriate extension to that new filename string. This can easily be done using the following PHP code:


$image = './uploads/files/imagefile.jpg';

$info = pathinfo($image);
		
// get the filename without the extension
$image_name =  basename($image,'.'.$info['extension']);

// get the extension without the image name
$ext = end(explode('.', $image));

echo $image_name; // this will display 'imagefile'
echo $ext; // this will display '.jpg'

Now, with this you'll have the image name stored in $image_name and the extension stored in $ext and you can feel free to manipulate either string to your liking.

I'm Tony, a developer and designer in Southwest Florida. I run DevDojo, build things for people who build with Laravel, and write about it from time to time.

Everyday thoughts go on X