php get file extension from url

Is there any way to get the file extension from a URL

I want to know that for make sure that the file that will be download from my script will have the extension I want.

The file will not be at URLs like:

Or maybe yes, but, I think that I will only use that kind of URL:

So, what do you recommend me to do?

php get file extension from url. Смотреть фото php get file extension from url. Смотреть картинку php get file extension from url. Картинка про php get file extension from url. Фото php get file extension from url

php get file extension from url. Смотреть фото php get file extension from url. Смотреть картинку php get file extension from url. Картинка про php get file extension from url. Фото php get file extension from url

7 Answers 7

It is weird, but it works:

but as crono remarked below, it will not work with parameters:

here’s a simple one I use. Works with parameters, with absolute and relative URLs, etc. etc.

Unit test if you will

Tune for your own needs.

P.S. Do not use Path.GetExtension cause it does not work with query-string params

I know that this is an old question, but can be helpful to people that see this question.

The best approach for getting an extension from filename inside an URL, also with parameters are with regex.

You can use this pattern (not urls only):

Explanation:

Example:

So you can use a strong pattern for urls like this:

Explanation:

Example:

php get file extension from url. Смотреть фото php get file extension from url. Смотреть картинку php get file extension from url. Картинка про php get file extension from url. Фото php get file extension from url

If the download link is something like http://example.com/this_url_will_download_a_file then the filename will be contained as part of the Content-Disposition, a HTTP header that is used to suggest a filename for browsers that display a «save file» dialog. If you want to get this filename then you can use the technique suggested by Get filename without Content-Disposition to initiate the download and get the HTTP headers, but cancel the download without actually downloading any of the file

Here is my solution:

First, I verify that my url is a valid url, then I get the file extension from the local path.

Some have suggested requesting the file from the url and checking the headers. That’s overkill for something so simple in my opinion so.

VirtualPathUtility.GetExtension(yourPath) returns the file extension from the specified path, including the leading period.

php get file extension from url. Смотреть фото php get file extension from url. Смотреть картинку php get file extension from url. Картинка про php get file extension from url. Фото php get file extension from url

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.

Источник

PHP- Get file type by URL

I want to get the file type (eg. image/gif) by URL using PHP.I had tried

The above code gave me a blank page and the following code returned «3»:

Where am I going wrong? Solved: using Fileinfo to fetch content type

7 Answers 7

Here is a PHP function I came up with:

php get file extension from url. Смотреть фото php get file extension from url. Смотреть картинку php get file extension from url. Картинка про php get file extension from url. Фото php get file extension from url

It returned 3 because png response type as maciej said.

Try this to get like this image/png :

php get file extension from url. Смотреть фото php get file extension from url. Смотреть картинку php get file extension from url. Картинка про php get file extension from url. Фото php get file extension from url

php get file extension from url. Смотреть фото php get file extension from url. Смотреть картинку php get file extension from url. Картинка про php get file extension from url. Фото php get file extension from url

You are not going wrong anywhere. exif_imagetype returns the value of one of the image type constants: http://php.net/manual/en/image.constants.php

If you would like to convert this to an extension string, you could use a switch statement:

You may want to change the order to most to least frequently expected for better performance.

the best way for my understanding

is to create function depend on finfo class

php get file extension from url. Смотреть фото php get file extension from url. Смотреть картинку php get file extension from url. Картинка про php get file extension from url. Фото php get file extension from url

In the first example, you’re getting a blank page because you’re not doing anything with the return value from the function call. In the second example, you’re getting a valid response. See the manual page for exif_imagetype() for a list of what the values mean.

exif_imagetype returns the image type. The response, 3, indicates it is IMAGETYPE_PNG, the correct response.

Источник

pathinfo

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

pathinfo — Возвращает информацию о пути к файлу

Описание

Подробнее о получении информации о текущем пути, можно почитать в разделе Предопределённые зарезервированные переменные.

Список параметров

Если flags не указан, то возвращаются все доступные элементы.

Возвращаемые значения

Если path содержит больше одного расширения, то PATHINFO_EXTENSION возвращает только последний и PATHINFO_FILENAME удаляет только последнее расширение. (смотрите пример ниже).

Если path не содержит расширения, то не будет возвращён элемент extension (смотрите ниже второй пример).

Если basename параметра path начинается с точки, то все последующие символы интерпретируются как расширение файла ( extension ) и имя файла filename будет пустым (смотрите третий пример).

Примеры

Пример #1 Пример использования функции pathinfo()

Результат выполнения данного примера:

Результатом выполнения данного примера будет что-то подобное:

Пример #3 Пример pathinfo() для файла, начинающегося с точки

Результатом выполнения данного примера будет что-то подобное:

Смотрите также

User Contributed Notes 37 notes

// result:
// string(11) «lib.inc.php»
// string(15) «/www/htdocs/inc»
?>

pathinfo() is locale aware, so for it to parse a path containing multibyte characters correctly, the matching locale must be set using the setlocale() function.

Reality:
var_dump(pathinfo(‘中国人2016.xls’));
exit();
array(4) < 'dirname' =>string(1) «.» ‘basename’ => string(8) «2016.xls» ‘extension’ => string(3) «xls» ‘filename’ => string(4) «2016» >

Expect(Solve):
setlocale(LC_ALL, ‘zh_CN.UTF-8’);
var_dump(pathinfo(‘中国人2016.xls’));
exit();
array(4) < 'dirname' =>string(1) «.» ‘basename’ => string(17) «中国人2016.xls» ‘extension’ => string(3) «xls» ‘filename’ => string(13) «中国人2016» >

Use this function in place of pathinfo to make it work with UTF-8 encoded file names too

Here is a simple function that gets the extension of a file. Simply using PATHINFO_EXTENSION will yield incorrect results if the path contains a query string with dots in the parameter names (for eg. &x.1=2&y.1=5), so this function eliminates the query string first and subsequently runs PATHINFO_EXTENSION on the clean path/url.

Checked with version 5.5.12:

It works fine with filenames with utf-8 characters, pathinfo will strip them away:

( pathinfo ( «/mnt/files/飛兒樂團光茫.mp3» ));
?>

.. will display:

Array
(
[dirname] => /mnt/files
[basename] => 飛兒樂團光茫.mp3
[extension] => mp3
[filename] => 飛兒樂團光茫
)

Note that this function seems to just perform string operations, and will work even on a non-existent path, e.g.

( pathinfo ( ‘/no/where/file.txt’ ));
?>

which will output:
Array
(
[dirname] => /no/where
[basename] => file.txt
[extension] => txt
[filename] => file
)

if you call pathinfo with a filename in url-style (example.php?with=parameter), make sure you remove the given parameters before, otherwise they will be returned as part of the extension.

unexpected, but longtime (all versions?) consistent, behaviour with trailing slash (Linux):

with Linux I am used, to add a trailing slash,
or just to keep that of the command line completion by [TAB],
to avoid mistyping a path on cp or mv with a same filename instead of a directory

// using php tags here only for syntax highlighting

php > var_dump ( pathinfo ( ‘/home/USER/www.2021-05/’ ));
array( 4 ) <
[ «dirname» ]=> string ( 10 ) «/home/USER»
[ «basename» ]=> string ( 11 ) «www.2021-05»
[ «extension» ]=> string ( 7 ) «2021-05»
[ «filename» ]=> string ( 3 ) «www»
>

When you need to get the file extension to upload a file with a POST method, try this way:

//[‘tmp_name] gets the temporal name of the file (not the real name), which will be used later

//Here is the magic of pathinfo to get the file extension

Источник

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:

php get file extension from url. Смотреть фото php get file extension from url. Смотреть картинку php get file extension from url. Картинка про php get file extension from url. Фото php get file extension from url

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:

Источник

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

php get file extension from url. Смотреть фото php get file extension from url. Смотреть картинку php get file extension from url. Картинка про php get file extension from url. Фото php get file extension from url

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:

php get file extension from url. Смотреть фото php get file extension from url. Смотреть картинку php get file extension from url. Картинка про php get file extension from url. Фото php get file extension from url

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:

php get file extension from url. Смотреть фото php get file extension from url. Смотреть картинку php get file extension from url. Картинка про php get file extension from url. Фото php get file extension from url

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 :

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *