User:Bcoughlan/Login with curl
Note : this is not updated and don't work ... you will got a beautifull "Fetching a token via action=login is deprecated. Use action=query&meta=tokens&type=login instead." error...
Log in through the MW API. Tested on MW 1.16
Updated for MW: 1.26.0
Different versions of mediawiki seems to be able to have the api.php in different locations - changed location for MW 1.26.0
Dont close the connection to the server ($ch) before you run the request against it the second time or curl, will initiate a new connection and give you a new session (token) - moved $ch out of func and globalled it.
Usage
edittry { global $settings; $token = login($settings['user'], $settings['pass']); login($settings['user'], $settings['pass'], $token); echo ("SUCCESS"); } catch (Exception $e) { die("FAILED: " . $e->getMessage()); } curl_close($ch);
$settings['wikiroot'] = "http://my.domain"; $settings['user'] = "myUser"; $settings['pass'] = "myPass"; $settings['cookiefile'] = "cookies.tmp"; $ch = curl_init(); // dont close this, before you got your login verified
function httpRequest($url, $post="") { global $settings;
global $ch;//Change the user agent below suitably
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9');curl_setopt($ch, CURLOPT_URL, ($url)); curl_setopt( $ch, CURLOPT_ENCODING, "UTF-8" ); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt ($ch, CURLOPT_COOKIEFILE, $settings['cookiefile']); curl_setopt ($ch, CURLOPT_COOKIEJAR, $settings['cookiefile']); if (!empty($post)) curl_setopt($ch,CURLOPT_POSTFIELDS,$post); //UNCOMMENT TO DEBUG TO output.tmp //curl_setopt($ch, CURLOPT_VERBOSE, true); // Display communication with server //$fp = fopen("output.tmp", "w"); //curl_setopt($ch, CURLOPT_STDERR, $fp); // Display communication with server
$xml = curl_exec($ch);
if (!$xml) { throw new Exception("Error getting data from server ($url): " . curl_error($ch)); }
return $xml; }
function login ($user, $pass, $token='') { global $settings;$url = $settings['wikiroot'] . "/api.php?action=login&format=xml";
$params = "action=login&lgname=$user&lgpassword=$pass"; if (!empty($token)) { $params .= "&lgtoken=$token"; }
$data = httpRequest($url, $params);
if (empty($data)) { throw new Exception("No data received from server. Check that API is enabled."); }
$xml = simplexml_load_string($data);
if (!empty($token)) { //Check for successful login $expr = "/api/login[@result='Success']"; $result = $xml->xpath($expr);
if(!count($result)) { throw new Exception("Login failed"); } } else { $expr = "/api/login[@token]"; $result = $xml->xpath($expr);
if(!count($result)) { throw new Exception("Login token not found in XML"); } }
return $result[0]->attributes()->token; }