Get file by extensions php

PHP: File extension to MIME type? [duplicate]

I’m aware of how to get the MIME type of a given file, but is there a way to do it given only an extension? Example input:

I do not think it’s a duplicate, as drrcknlsn wants to get the mime type from the extension while the question (which this is marked as duplicate of) does the opposite, finding the extension for a mime type.

Clearly, as @Alex says. How is this a duplicate of the linked answer, if that one wants the (list of!) extensions for a MIME type, while this one needs the inverse function: get the MIME type for an extension?!

3 Answers 3

try this to get info about which extension is which mime type, but of course please be aware that this won’t be very accurate (e.g. possible gif file on png extension..)

I ended up rolling my own method, but thanks for letting me know about /etc/mime.types ! That was the ticket.

Even if you aren’t using Apache, it would be easy enough to get the mime.types file and query directly against it. I was going to suggest creating a temporary file and querying against it in the normal way, but loading a list of mime types and doing a lookup would be better.

I don’t have the Fileinfo extension installed, but from PHP documentation, it seems like Fileinfo might give you that information, which was previously given by the deprecated function mime_content_type()

This question is in a collective: a subcommunity defined by tags with relevant content and experts.

Источник

Best way to get files from a dir filtered by certain extension in php [duplicate]

That, however, retrieves every file in a directory. How would I retrive only files with a certain extension such as .ini in most efficient way.

Читайте также:  Css if only one child

//path to directory to scan $directory = «../file/»; //get all image files with a .text extension. $images = glob($directory . «*.text «); //print each file name foreach($images as $image) < echo $image; >

7 Answers 7

PHP has a great function to help you capture only the files you need. Its called glob()

glob — Find pathnames matching a pattern

Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.

$files = glob("/path/to/folder/*.txt"); 

This will populate the $files variable with a list of all files matching the *.txt pattern in the given path.

@Lix why not to use $files = glob(«/path/to/folder/*.txt») directly without for ?. I think it’s the same

@MohamadOsama — You’re absolutely right 🙂 Always fun to look back 8 years at my old code haha! Thanks for the feedback!

If you want more than one extension searched, then preg_grep() is an alternative for filtering:

 $files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir_f)); 

Though glob has a similar extra syntax. This mostly makes sense if you have further conditions, add the ~i flag for case-insensitive, or can filter combined lists.

This answer was extremely helpful for me! I was trying to search for hundreds of different file identifiers and files in a folder with tens to hundreds of thousands of files. glob couldn’t handle such a big search string, and if I broke into into smaller strings and looped it took several minutes. using preg_grep with scandir takes about 5 seconds!

Thanks for introducing preg_grep to me. This is much more helpful as compared to glob it can handle case insensitives.

Источник

PHP Search & Get Files (By Extension, Prefix, Name, Date)

So you have a project that needs to filter out a list of files from a folder – The glob() function is probably your best bet, but it can be pretty intimidating for some beginners. Fear not, here are some of the common “search patterns” that I gathered from the Internet. Read on!

TLDR – QUICK SLIDES

PHP Get Filter Files List

TABLE OF CONTENTS

PHP GLOB SEARCH/FILTER FILES

All right, let us now get the common examples of filtering a list of files using PHP glob.

1) GET BY FILE EXTENSION

", GLOB_BRACE); print_r($images); // (D) GET ALL DOCUMENTS $docs = glob($dir . "*.", GLOB_BRACE); print_r($docs);
  • To get a specific type of file – glob(«PATH/*.EXT») .
  • If you want to get a list of file extensions, use GLOB_BRACE to help you – glob(«PATH/*.», GLOB_BRACE) .
Читайте также:  Pack and unpack python

2) GET BY FILE PREFIX & SUFFIX

*", GLOB_BRACE); print_r($prefix); // (D) GET ALL FILES ENDING WITH "_J" $suffix = glob($dir . "*_j.*"); print_r($suffix); // (E) GET ALL FILES STARTING WITH I_ AND ENDING WITH "_J" $presuf = glob($dir . "i_*_j.*"); print_r($presuf);
  • To get files starting with a certain prefix – glob(«PATH/PREFIX*») .
  • If you have multiple prefixes, use GLOB_BRACE once again to help you – glob(«PATH/», GLOB_BRACE) .
  • To get files ending with a certain suffix – glob(«PATH/*SUFFIX.*») .
  • To get files starting with a certain prefix and ending with a certain suffix – glob(«PATH/PREFIX*SUFFIX.*») .

P.S. You can further filter by the file extension if you want. For example, glob(«PATH/PREFIX*.», GLOB_BRACE) .

3) GET BY FILE NAME

  • To search by the file name (case sensitive) – glob(«FOLDER/*SEARCH*») . I.E. It’s a match as long as the file name contains SEARCH anywhere.
  • Case-sensitive search is kind of painful, you will have to manually use square brackets to match each character – glob([aA][bB][cC][. ])

4) GET FILES BY DATE

 > // (C) GET FILES CREATED ON EXACT DATE $start = strtotime("2012-12-12 00:00:00"); $end = strtotime("2012-12-12 23:59:59"); foreach (glob($dir . "*.*") as $file) < $filetime = filemtime($file); if ($filetime>=$start && $filetime <=$end) < echo "$file"; >>

Sadly, glob() cannot filter by the file date “natively”. We will have to manually loop through all the files and check the timestamp individually.

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

SUPPORT

600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

A SMALL NOTE ON PERFORMANCE & READING SUB-FOLDERS

Take note of how glob() works, it returns an array. It’s all nice and cool but runs into memory issues when you deal with massive folders. There is a way around it by using an iterator, check out my other “ways to list files folders” tutorial below – Which also covers “how to read sub-folders”.

Читайте также:  Npm redux toolkit typescript

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Источник

finding extension of the file being uploaded using php

I am using PHP for a website. I have to get users upload their pics. Now, the pics can be in jpeg or png or gif format. My problem is that i identify a user by a unique userid, so I want to save the pics as: userid.jpg or userid.png etc. Now, how do i find out the extension of the file selected by the user using php?

10 Answers 10

I wouldn’t rely on the file extension provided by the visitor. Instead, ask the file itself what it is (this can still be spoofed, but its less likely; also you don’t have to wonder if the extension is 3 or 4 characters (jpeg, jpg for example)). Try:

if ($_FILES['avatar']['type'] == "image/gif") if ($_FILES['avatar']['type'] == "image/jpeg") if ($_FILES['avatar']['type'] == "image/png") 

They’re much more reliable.

No! Be very careful doing this. Make sure the extension is of a relevant type (gif/jpg/png) as well, and not something possibly executable (like .php).

Instead of relying on the extension sent by the client, you can also determine the type of the file, using fileinfo (PHP >= 5.3), or if you’re using an older version of PHP, something like mime_content_type

Once you have the mime-type of the file, it’s just a matter of mapping (like ‘image/png’ => ‘png’)

(Should actually be better for security reasons ; if I remember correctly, $_FILES[‘. ‘][‘type’] is sent by the client, and can be faked)

If you’re running a nicely updated server with PHP 5.3, you should look into the new File Information extension. It’ll look at the files themselves and try to determine the mime type, from which you can get the extension. This is more reliable than looking at the extension or mime type as provided by the browser, as both of these can be faked.

An ideal solution could use a combination of all of these methods for maximum effectiveness.

Источник

Оцените статью