Login To Specific WordPress Page With cURL

I’ve got a WordPress blog that is setup to require login to view any content on it. This is an internal tool, but we wanted it accessible externally. This works, no problem.

But with this setup, good luck accessing the RSS feed.

Read More

I figure it shouldn’t be rocket science to login with curl, then request the desired page and output it. This script will live on an internal webserver, so you can get your RSS feed internally (so users that use Outlook, like the owner, can view it when connected to the network).

I’ve looked at a whole bunch of tutorials and questions on how to do this, with no luck (here are a few of them). None of them seem to have a complete script. They all do bits and pieces, I just can’t it to all work together.

Here’s what I have so far:

$username='dummyUser';
$password='dummyPassword';
$url='http://url.wordpress.org/';

$postdata = 'log='. $username .'&pwd='. $password .'&wp-submit=Log%20In&redirect_to='. $url .'wp-admin/&testcookie=1';
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url . 'wp-login.php');
curl_setopt ($ch, CURLOPT_HEADER, 1);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6');
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_REFERER, $url . 'wp-admin/');
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_POST, 1);
$result = curl_exec ($ch);

$end = strpos($result, 'Content-Type');
$start = strpos($result, 'Set-Cookie');
$parts = split('Set-Cookie: ',substr($result, $start, $end-$start));
$cookies = array();
foreach ($parts as $co) {
    $cd = split(';',$co);
    if (!empty($cd[0]))
        $cookies[] = $cd[0];
}


curl_setopt ($ch, CURLOPT_URL, $url . 'feed/');
curl_setopt ($ch, CURLOPT_COOKIE, implode(';',$cookies));
curl_setopt ($ch, CURLOPT_HEADER, 0);
$result = curl_exec ($ch);

echo $result;

The end result I’m getting is just the login screen displayed, so I’m guessing something’s going weird with the cookies (I tried to follow this example). Anyone that can see what I’m missing would be greatly appreciated.

Related posts

Leave a Reply

1 comment