How to get file extension - PHP
Last updated: Aug 24, 2022
Colleagues hello to all.
In today's article, we'll talk about how you can determine file extensions in PHP.
In your development, you will often encounter the task of obtaining a file extension, for example, when uploading a file to a server. When saving a file on a server, there is also a very common task to save the file not with the original name, but to set a unique value as the filename so that the filename does not match other files on the server.
There are a lot of different options for solving this problem, and I'll show you them. As an example, I will show all the actions on three files, the first file will be a file with .txt extensions, the second will be images with .png extensions and the third option will also be images, but with .jpeg extensions.
For convenience, I will use variables that will contain the names of the files with which we will work and their extensions will be obtained. I also created a function called get_file_extension, in which I will put code that will print file extensions to the console.
In the first variant of getting the file extension we will use the functions mb_strtolower, mb_substr. The mb_strtolower function takes a string as a parameter and converts all characters in that string to lowercase. The second function mb_substr takes the same string and returns part of the string.
php> mb_strtolower(mb_substr(mb_strrchr($file_name, '.'), 1));
The second option is to use the pathinfo function. The pathinfo function returns information about a file as an array, such as filename, basename, extension, dirname. All this information is not important to us now, we want to get only extensions, for this we can pass a special flag PATHINFO_EXTENSION as the second parameter, which indicates that the function should return only file extensions as a string, and not all information in the form array.
php> pathinfo($file_name, PATHINFO_EXTENSION);
The next way to get the file extension is to use the array_pop and explode functions.
php> array_pop(explode('.', $file_name));
First, the explode function splits the string into an array by the delimiter, in this case, we split it with a dot, and then the array_pop function returns the last element from this array, and the last element of the array is just our extension.
The next option to get the file extension is to use the SplFileInfo class. The SplFileInfo class has many different methods to provide different information about a file, we need to use one of its methods called getExtension.
php> $info = new SplFileInfo($file_name);
Thank you all, I hope that my article helped you in some way.