Roan Kattouw schreef:
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; }
As it turns out, you can throw out that function and use $snoopy->setCookies(); instead. Snoopy's better than I thought. Improved version of the script follows below.
Catrope
== PHP code starts here == <?php require_once('Snoopy.class.php');
$wikiPath = "http://en.wikipedia.org/w"; $apiPath = "$wikiPath/api.php";
$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}");
// We're only really interested in the cookies $snoopy->setcookies();
$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>";