Get File Names by Extension in CodeIgniter

If you’re building a bespoke website or web application, it’s likely that you will at some point need to deal with user-uploaded files. CodeIgniter’s File Helper gives you some useful functions for the bread-and-butter operations — reading, writing, deleting and the like.

The get_filenames function allows you to get a list of all the files in a specific directory, which is great, but what it doesn’t do is allow you to filter the results by file extension. For example, if you want to allow users to upload large files via FTP and then attach them to specific records in your database, you’ll need to give them some way of seeing what files are on the server. The simplest solution is to give them a drop-down menu with the file names as options.

But what if the user uploads an incorrect file type? The standard get_filenames() would return all files in the directory, so these files would be available for selection. You need to check the chosen filename when validating the form for security purposes, but for neatness and usability you should also filter the dropdown so that only valid file types are allowed. Why let the user select an invalid file, only to get kicked back to an error message, when we can stop them selecting it in the first place?

The Solution

To do this, we’re going to “extend” the File Helper to add a new function, get_filenames_by_extension(). This function will take three arguments — the directory to search, the allowed file extensions, and a boolean to return the full file paths or not, as with the standard get_filenames().

The first step in extending the helper is to create the file MY_file_helper.php in your application/helpers directory. Once that’s done, copy over the original get_filenames function from system/helpers/file_helper.php. Rename it to get_filenames_by_extension() and add a parameter called $extensions after the first parameter, $source_dir . When we call the function, $extensions will be an array containing the different extensions that we want to be included in our results.

Because this is a recursive function, we’ll also need to modify the function call at the point of recursion. Look for the following line:

get_filenames($source_dir.$file.DIRECTORY_SEPARATOR, $include_path, TRUE);

and modify it so that it calls get_filenames_by_extension() and includes our new $extensions parameter. If you forget this step, you can get some odd behaviour so beware!

Now we need to actually check to make sure the file names that get output by the function have extensions that match what we specify in $extensions.

We do this by using PHP’s pathinfo function. With the following snippet of code:

pathinfo($file, PATHINFO_EXTENSION);

we can easily find the extension of any file that we pass in. With this in mind, look for the following line in our function:

$_filedata[] = ($include_path == TRUE) ? $source_dir.$file : $file;

and replace it with:

if(in_array(pathinfo($file, PATHINFO_EXTENSION), $extensions))
	$_filedata[] = ($include_path == TRUE) ? $source_dir.$file : $file;

— this stops any unwanted files making it into our output array.

The final code should look like this.


Now the function is ready for use. Using it is just like using the standard get_filenames(), except you have to specify an array of file extensions to filter by, like this:

$extensions = array('jpg', 'jpeg', 'png' 'gif');
$filenames = get_filenames_by_extension('uploads/', $extensions);

If you forget to specify an array you’ll get an error, as we’re not specifying a default in our function definition. You can add one if you like, but I think it’s better to flag up what is probably a mistake rather than run the risk of allowing unwanted files to slip through.

Note that the array is a list of extensions to include in our output. This is preferable to having an exclusive list, because the file types you accept are unlikely to change much, whereas anyone can make up a gibberish file extension and have it show up in the list, which is not what we want.

Wrapping Up

Simple, no? The filtered file lists make the interface neater for our users, and also serve as the first line of validation - if a user uploads an invalid file, they simply won’t see it in the list for selection.

One caveat though - don’t use this as your only method of stopping naughty people using malicious files - there need to be checks further down the line too, as it’s trivial for someone to POST a value that isn’t in the list. This is a usability tweak, not a security patch!

Tags: CodeIgniter Files Helpers PHP Usability

Found this post useful or interesting? Please share it with your friends!


Sorry, feedback is now closed on this post, but please feel free to get in touch if you would like to talk about it!

  1. Pingback: Twitter Trackbacks for Get File Names by Extension in CodeIgniter on 24th November 2010 at 10:09am

    Get File Names by Extension in CodeIgniter - Simian Studios Blog

Or find posts by tag →

Friends & Influences

  1. Aching Brain
  2. Andy Budd
  3. Anthony Killeen
  4. Ben Everard
  5. Cameron Moll
  6. Dan Cederholm
  7. Dan Mall
  8. Dave Shea
  9. Elliot Jay Stocks
  10. Jamie Knight
  11. Jamie Rumbelow
  12. Jason Santa Maria
  13. Jeff Croft
  14. Jeffrey Zeldman
  15. Jeremy Keith
  16. Jon Hicks
  17. Khoi Vinh
  18. Mark Boulton
  19. Matt Croucher
  20. Nocturnal Monkey
  21. Sarah Parmenter
  22. Shaun Inman
  23. Simon Collison
  24. Tim Van Damme
  25. Toby Howarth