I’m using an external CSV reading library that takes a filehandle (resource) as an argument. I’m using wp_handle_upload() to actually process and store the file in the Uploads directory, but that returns the file path, not a resource.
Is $filehandle = fopen( $file['file'], 'r' )
acceptable here, or is there a better WP alternative? I don’t see anything that fits the bill in file.php
, or anywhere else I’ve looked.
What follows is kind of complicated. You can probably just use
fopen
orfile_get_contents
without any issues.There’s the filesystem api. Which deals with determining ownership of a file and returning the correct way of accessing it — most of the time that just means normal PHP functions (or the direct filesystem class).
Otto has a nice tutorial on this which I’m copied/altered to figure out how it works for this answer.
Essentially you use
request_filesystem_credentials
to get the appropriate information to interact with the file system. This might be nothing (eg. direct, see the link above) or it may show a form to the user so they can enter the username/password for FTP or SSH. Depends on your server setup.Some quick examples. Let’s add an admin page, with a simple form.
The
wpse74395_use_filesystem
function:The comments should help explain what’s going on. Essentially: make sure we’re in a POST request (form submission), and the request checks out (nonce validation). From there, we’ll try to get filesystem credentials. If we don’t get any, a form will show to collect them, so stop the rest of the page from showing.
By only giving
request_filesystem_credentials
the first argument, we’re letting WP decide what method we need to use. Most of the time this is direct and the user won’t see anything. Please note thatrequest_filesystem_credentials
will do everything it can to get the stuff without asking the user — database options, config options, etc.Once we have the creds, try to initialize the global
$wp_filesystem
object withWP_Filesystem
. If it works, awesome! If not, try to get the credentials again.If everything checks out, use the
$wp_filesystem
as you need to. They all have a consistent interface. Here’s the above code in a plugin.WordPress do not use
fopen()
. The WordPress filesystem uses four methods to access a file:file_get_contents()
(method direct)ftp_connect()
/ftp_ssl_connect()
(method ftpext)ssh2_connect()
(method ssh2)You have to create the filehandle on your own with
fopen()
. When you usewp_handle_upload()
, than WordPress should have sanitized and verified the file.$file['file']
should be clean and usable.