More on Working with CSV Files in WordPress

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?

3 Replies to “More on Working with CSV Files in WordPress”

  1. If you’re reading from CSV files, I highly recommend using the parsecsv library. Unsurpassed (no pun intended!)

    https://github.com/parsecsv/parsecsv-for-php

    When sending CSV to the browser and expecting it to load “nicely” in Microsoft Excel (which, let’s face it, is more often than not, and certainly more often than I’d like), your best bet is to output everything in UTF-16LE (Unicode with 16-bit words, low-byte encoded). The trick is to tell receivers that’s what is coming:

    header(‘Content-Encoding: UTF-16LE’);

    header(‘Content-Type: text/csv; charset=UTF-16LE’);

    echo “\xFF\xFE”; // UTF-16LE BOM

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.