1

I'm trying to login via the api but allways get a "badtoken" error ("Invalid token"). I've followed the complete guide on the Mediawiki/Api-Help and do exactly what they suggest.

  1. I get the login-token:
  2. I do the POST request for the clientlogin.

Here is my code:

$wiki = 'example.de/wiki/'; 
$api = $wiki.'api.php?';
$retry = false;
$wpName = 'someone'
$wpPassword = 'supersave';

$json_a = (file_get_contents($wiki.'api.php?action=query&meta=tokens&type=login&format=json');
$json_b = json_decode($json_a,true);
$token = $json_b['query']['tokens']['logintoken'];
echo("\nToken: ".$token."\n");

$data = array(
        'action'               => 'clientlogin',
        'loginreturnurl'       => $wiki,
        'logintoken'           => $token,  
        'username'             => $wpName,
        'password'             => $wpPassword,
        'rememberMe'           => 1); 

$ch = curl_init($api);
$postString = http_build_query($data, '', '&');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
# Get the response
$response = curl_exec($ch);
curl_close($ch);   

Does anyone knows what to do to perform the login?

Chris Dji
  • 67
  • 8
  • 2
    You need to do everything in the same session. Use curl for both requests and use CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR for both of them. – Tgr May 29 '17 at 23:24
  • Also, clientlogin is not really meant for non-interactive login. It's better to use action=login and [bot passwords](https://www.mediawiki.org/wiki/Manual:Bot_passwords). – Tgr May 29 '17 at 23:26
  • `login` is deprecated – lolololol ol Nov 14 '22 at 17:35

0 Answers0