php get file extension from file
PHP: Get the extension of a file.
This is a quick guide on how to the extension of a file using PHP. In this tutorial, we will be using PHP’s pathinfo function instead of one of those nasty error-prone ‘hacks’ that you will come across on the Internet.
Getting the extension.
The pathinfo function returns information about a given file path. You can use it to get the directory name, the base name, the file name and the extension. In our case, we want the extension.
Take a look at the following example:
In the code above, we supplied the pathinfo function with the constant PATHINFO_EXTENSION. As a result, it returns the string “txt”.
What if there is no extension?
If there is no extension, then the pathinfo function will return an empty string:
If you run the snippet above, you will see that the following is outputted:
Multiple periods / dots.
This approach will also work if the file in question has multiple periods or dots. Take a look at the following example:
In the example above, our filename contains two periods. However, the pathinfo function is still able to return the correct extension name.
Special characters.
If there is a chance that your filename might contain special multibyte characters, then you will need to set the matching locale information. This is because the pathinfo function is “locale aware.”
You can do this by using PHP’s setlocale function like so:
Получить расширение файла в PHP
В данной статье я расскажу очень простые способы, как можно получить расширение файла средствами PHP. Опишу все подробно. Для начала заносим название файла в переменную:
Далее нам поможет функция Explode с помощью которой разбиваем строку на подстроки.
В качестве разделителя используется символ точки (.), То есть символ разделения названия файла от его расширения.
Последнее что нужно, это взять последний элемент массива. В этом нам поможет функция End:
Вот и все, теперь в переменной $mime содержаться значение расширения файла.
В данном случае мы видим как результат работы функции Explode передается непосредственно как параметр в функцию End. Но функция End работает с указателем на массив, а не со значением массива.
Для решения необходимо сперва перенести значение в временную переменную, и только потом передаем в End указатель на эту переменную.
Собственно все ошибки подобного рода решаются именно таким образом. Если в вашей программе где-то стала вылетать вышеуказанная ошибка, то просто создавайте временную переменную.
Таким же способом можно получить расширения файла, но вместо функции End используется функция Array_pop:
Функция Array_pop удаляет элемент в конце массива, то есть не только возвращает последнее значение массива. На одну операцию выполняется более чем с функцией End, но разница настолько маленькая, что на это даже не стоит акцентировать внимание.
Выполнить поиск расширения можно используя вместе функцию Substr и функцию Strrpos:
Чтобы избавиться самой точки в полученном подстроке, увеличиваем начало старта на одно смещение вправо (1).
Существует также функция Pathinfo, с помощью которой можно получить расширение файла. По моему мнению, это лучший вариант. Для этого выполняем простой код:
Здесь описаны простые способы получения расширение файла, но помните, это только для ознакомления, или даже для демонстрации возможностей языка PHP. На самом деле, вам самим решать, каким образом использовать для различных случаев возможен особый подход.
PHP Function To Get A File Extension From A String
Getting the file extension from a PHP string can be very important in validating a file or file upload. I’ve written a simple PHP function to retrieve a file extension from a string.
The Code
This simple method of file extension retrieval should be reused throughout your code.
Recent Features
Detect DOM Node Insertions with JavaScript and CSS Animations
An Interview with Eric Meyer
Incredible Demos
Link Nudging with CSS3 Animations
MooTools Window Object Dumping
Discussion
This looks really useful, thanks.
I came up with this snippet to get the file extension as well, using array functions:
… and it got cut out. Here’s the function, without tags:
As mentioned by ochronus the following code does the exact same thing:
or we can do it via end(explode(‘.’, «filename.ext»)); easily
File extension from path:
What happens when you try to get the extension of “/etc/init.d/README” with the explode method?
Just use the pathinfo().
Oh come on…i wrote this post quickly.
lol. Why?!
Just use the pathinfo().
I don’t like rhetoric. You asked why? Could be many reasons. You just need some imagination.
– Didn’t know about pathinfo (could be many reasons for this. New to PHP, came frmo a different language, simply has a knowledge gap)
– Did not know what pathinfo could do (it’s not well documented)
– Wrote the routine just for fun to improve programming skills (not used in actual project)
@Jorge: Either way works, and it just ends up being a matter of preference. You have to consider how this function will usually be used on a web application; it will be grabbing the extension and making sure it’s an allowed extension for upload. Thus, the explode method would return something that doesn’t match a valid extension (like your README example), and the file upload would get declined.
If you’re building a file explorer on the web, sure, use pathinfo(); that’s common sense. If you’re building a web app that takes uploads, then I can’t imagine the explode method would not be faster than pathinfo.
How can I change a file’s extension using PHP?
How can I change a file’s extension using PHP?
Ex: photo.jpg to photo.exe
11 Answers 11
In modern operating systems, filenames very well might contain periods long before the file extension, for instance:
PHP provides a way to find the filename without the extension that takes this into account, then just add the new extension:
Will change any extension to what you want. Replace png with what ever your desired extension would be.
Replace extension, keep path information
Once you have the filename in a string, first use regex to replace the extension with an extension of your choice. Here’s a small function that’ll do that:
Then use the rename() function to rename the file with the new filename.
Just replace it with regexp:
You can also extend this code to remove other image extensions, not just bmp:
For regex fans, modified version of Thanh Trung’s ‘preg_replace’ solution that will always contain the new extension (so that if you write a file conversion program, you won’t accidentally overwrite the source file with the result) would be:
Changes made only on extension part. Leaves other info unchanged.
Or for all extensions:
Many good answers have been suggested. I thought it would be helpful to evaluate and compare their performance. Here are the results:
Just as a note, There is the following solution too which took 0.000014066696166992 seconds. Still couldn’t beat substr_replace :
PHP file_put_contents get file extension/type
It’s possible to get extension of a file with file_put_contents in PHP?
I want to download files from a server using php with cycle, but each file has a different type and I want to know if there is a way to understand the extension of each file?
How can I find out what type of a file, because if I put it with only the name becomes impractical?
3 Answers 3
I understand that you problems is that you do not know what extension to put for this file. Once you have saved the file then you can detect the mime type and extension like this
Once you have found the mime type then you can rename it. Of course bear in mind that this needs extra IO from your HDD.
maybe try smth like this:
A file transferred via HTTP may have a name in the Content-Disposition HTTP header. If it doesn’t, there should be a Content-Type HTTP header which at least tells you the MIME type of the file; you can map that to a file extension and need to make up some filename yourself. If neither are present, you’re on your own.
The first step is to read the HTTP headers before downloading the HTTP body. The curl extension can do that, get_headers could do it (though requires an additional roundtrip), or other socket based HTTP libraries could do it (I’d recommend this one, you want to make one HTTP request, get access to the headers, but not read the entire file into memory). Look around for a library that can do this for you, this is a bit of a broad topic.
Not the answer you’re looking for? Browse other questions tagged php file-get-contents or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.