Authentication by POST/GET in WordPress

For a project I’m working on I needed to trigger an action in a remote WordPress installation. I had a bit of trouble understanding how I could authenticate myself against the remote site. Eventually I found a clean and nice way and I want to share it here with you. Of course, if you’re not into WordPress you can safely skip this post.

The Problem

Where I first stumbled was when from my plugin I tried to access directly the other plugin in the remote site. The code I was using for doing this was something like:

// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
// print the result of the whole request:
print "CONTENT = ".$output;

And this wouldn’t work because although I was authenticated in the remote site via the browser, the session that the curl request creates is not, and so this request results in us being redirected to the login page.

What to do?

Ideally we want to do a POST request that we execute before and that authenticates us. I searched around on how to do this but couldn’t find anything. What I found was one of the many third-party applications that allow talking to WordPress remotely. I then looked at how they work and how they authenticate themselves.

Instead of doing a POST request to the plugin page like before, they do a POST request to the site’s index.php. A plugin is registered to catch a particular POST request. Then you simple use the WordPress function user_pass_ok(), that authenticates the user against the database.

Here I demonstrate how to do this using a GET request, because its simpler, but the same thing would work with a POST request.

add_action('plugins_loaded', 'unpackimport_createblog', -1);
function unpackimport_createblog() {
if(isset($_GET['myplugin'])) {
if(user_pass_ok($_REQUEST['username'], $_REQUEST['password']))
echo 'Authentication successful';

And the client request:

curl_setopt($ch, CURLOPT_URL, "");


I wanted to show a working example rather than just saying this works so I did this screencast. You can also download the plugins yourself and try them out.