I've drawn up a simple script that logs in and fetches information using
the Snoopy class. Snoopy is available at
http://snoopy.sourceforge.net/
Simply download the tarball and extract the Snoopy.class.php file in the
same directory as your script. Most important is the getCookieHeaders()
function, which sets up the cookies correctly.
Hope this helps,
Catrope
== PHP code starts here ==
<?php
require_once('Snoopy.class.php');
$wikiPath = "http://en.wikipedia.org/w";
$apiPath = "$wikiPath/api.php";
function getCookieHeaders($headers)
{
// This function parses Snoopy's header array and returns a nice
array of cookies
$cookies = array();
foreach($headers as $header)
if(preg_match("/Set-Cookie: ([^=]*)=([^;]*)/", $header,
$matches))
$cookies[$matches[1]] = $matches[2];
return $cookies;
}
$snoopy = new Snoopy;
// Example 1: Build a table of namespaces
$request_vars = array(
'action' => 'query',
'meta' => 'siteinfo',
'siprop' => 'namespaces',
'sishowalldb' => '',
'format' => 'php' // NEVER, EVER, forget this one
);
if(!$snoopy->submit($apiPath, $request_vars))
die("Snoopy error: {$snoopy->error}");
$array = unserialize($snoopy->results);
$namespaceArr = $array['query']['namespaces'];
echo "<table
border>\n<tr><th>ID</th><th>Name</th></tr>\n";
foreach($namespaceArr as $ns)
echo
"<tr><td>{$ns['id']}</td><td>{$ns['*']}</td></tr>\n";
echo "</table>\n";
// Example 2: Get userinfo before and after login
$request_vars = array('action' => 'query', 'meta' =>
'userinfo',
'format' => 'php');
if(!$snoopy->submit($apiPath, $request_vars))
die("Snoopy error: {$snoopy->error}");
$array = unserialize($snoopy->results);
$userinfo = $array['userinfo'];
if(isset($userinfo['anon']))
echo "Anonymous user {$userinfo['name']}<br>";
else
echo "Registered user {$userinfo['name']}<br>";
echo "Logging in...<br>";
$request_vars = array('action' => 'login', 'lgname' =>
'yourusername',
'lgpassword' => 'yourpassword', 'format' => 'php');
if(!$snoopy->submit($apiPath, $request_vars))
die("Snoopy error: {$snoopy->error}");
// Fetch the cookies from the login request and tell Snoopy to use them
from now on
// This only has to be done once
$snoopy->cookies = getCookieHeaders($snoopy->headers);
$request_vars = array('action' => 'query', 'meta' =>
'userinfo',
'format' => 'php');
if(!$snoopy->submit($apiPath, $request_vars))
die("Snoopy error: {$snoopy->error}");
$array = unserialize($snoopy->results);
$userinfo = $array['userinfo'];
if(isset($userinfo['anon']))
echo "Anonymous user {$userinfo['name']}<br>";
else
echo "Registered user {$userinfo['name']}<br>";
== PHP code ends here ==