CSV files are a topic that I’ve previously discussed on this blog. But one of the things that come with sharing information in this format over time is that new information, strategies, or techniques can be learned.

CSV Files in WordPress

This is one of the challenges of others finding old content, isn’t it? But I digress on that.

For those who haven’t read my previous entries, you can see some of them here:

And it’s not that those are irrelevant. I might change a few things here and there, but that’s the purpose of this post. Instead, I want to build on some of the things mentioned above.

After all, working with CSV files in web applications is nothing new, and it’s not going anywhere anytime soon. So why not share some additional strategies that I’ve found useful in making my projects a bit more robust (and see what you have to add to it in the comments :).

CSV Files in WordPress

Anytime you’re working with CSV files you need to make sure that you’re doing all you can to ensure that you’re not allowing users to upload malicious files.

The problem is that it’s hard to detect if the file truly is a CSV file (without doing some extensive evaluation of the data), but there are some practical things we can do.

For example, you can check the MIME type of the incoming file. Take a look at the function below:

This will determine if the incoming file matches one of the acceptable MIME types. You can change the array, of course, to match your requirements.

Another more obvious strategy is to check the file extension. PHP provides some helpful functions for doing this, too:

Using these two functions, you can put together a public function that you can call:

And perhaps ultimately create a class for evaluating a file:

Note the class has no documentation to it (as I wanted to keep the code succinct) because I’ve described each function int his post. These are not the only ways to evaluate the validity of CSV files, though. There are additional checks you can do.

So if you have some to add, why not add them to the comments or comment on the linked gist?