Skip to content

Instantly share code, notes, and snippets.

@MineTheCube
Created June 16, 2016 13:22
Show Gist options
  • Save MineTheCube/99c54ac88a333a9e87592ec0c91327ac to your computer and use it in GitHub Desktop.
Save MineTheCube/99c54ac88a333a9e87592ec0c91327ac to your computer and use it in GitHub Desktop.
Authenticate with a Minecraft account
<?php
/**
* Authenticate with a Minecraft account
*
* After a few fails, Mojang server will deny all requests, so use a proxy to bypass that limit
*
* @example $account = authenticate('[email protected]', '123456', '107.170.58.132:3128');
*
* @param string $id Minecraft username or Mojang email
* @param string $password Account's password
* @param string $proxy Proxy address like: "ip:port"
* @return array|bool Array with id and name, false if authentication failed
*/
function authenticate($id, $password, $proxy = null) {
if (!function_exists('curl_init') or !extension_loaded('curl')) {
return false;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://authserver.mojang.com/authenticate');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
if ($proxy) curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array(
'agent' => array(
'name' => 'Minecraft',
'version' => 1,
),
'username' => $id,
'password' => $password
)));
$output = curl_exec($ch);
curl_close($ch);
$json = json_decode($output, true);
if (!empty($json) and is_array($json) and array_key_exists('selectedProfile', $json) and is_array($json['selectedProfile'])
and array_key_exists('id', $json['selectedProfile']) and array_key_exists('name', $json['selectedProfile'])) {
return array(
'id' => $json['selectedProfile']['id'],
'name' => $json['selectedProfile']['name']
);
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment