PHP API Examples

From mediawiki.org
<?
    //Define Your Api Endpoint here
    $endPoint = "https://pathtoyourwiki/api.php";
    //Force HTTPS when your endpoint also uses HTTPS
    if(substr(strtolower($endPoint),0,5) == "https"){ForceHTTPS();}
    //Helper functions
    function ForceHTTPS()
    {
        if($_SERVER["HTTPS"] != "on")
        {
            $pageURL = "Location: https://";
            if ($_SERVER["SERVER_PORT"] != "80")
            {
                $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
            }
            else
            {
                $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
            }
            header($pageURL);
        }        
    }
    function ShowErrors()
    {
        ini_set('display_errors', 1);
        ini_set('display_startup_errors', 1);
        error_reporting(E_ALL);        
    }
    // API Implementation
    function GetLoginToken($username, $password, $endPoint, $cookieName, $cookieFile)
    {
        $endPoint.="?action=query&meta=tokens&type=login&format=json";
        $parameters = [];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $endPoint);
        curl_setopt($ch, CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
        //curl_setopt($ch, CURLOPT_POST, true);
        //curl_setopt($ch, CURLOPT_POSTFIELDS,  http_build_query($parameters));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_COOKIESESSION, true);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieName);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
        $json = curl_exec($ch);
        curl_close($ch);
        $arr =json_decode($json, true);
        return $arr['query']['tokens']['logintoken'];
    }
    //Define wiki bot & api endpoint
    /*
        In order to successfully use a bot, using the administrative account(of your media wiki installation), you need to navigate to: index.php?title=Special:BotPasswords
            1.) Create a new bot password(make note of the bot username, and password)
            2.) Define the username and password below with __BOT_USER_NAME__ and __BOT_PASSWORD__
        
        Additionally, navigate to : index.php?title=Special:UserRights
            1.) Search for your administrative account
            2.) Under 'Groups you can change', make sure the bot checkbox is checked
    */    
    define("__BOT_USER_NAME__", "");
    define("__BOT_PASSWORD__", '');
    define("__API_END_POINT_",$endPoint);    
    define("__COOKIE_NAME__", 'cookie-name');
    define("__COOKIE_FILE_PATH__", '/var/www/ip4.x/file/tmp');
    //Initialize Page
    ShowErrors();
    //Assign the result of calling the GetLoginToken function 
    $loginToken = GetLoginToken(__BOT_USER_NAME__,__BOT_PASSWORD__, __API_END_POINT_, __COOKIE_NAME__, __COOKIE_FILE_PATH__);
    //Echo the token
    echo "Login Token:<br><br>$loginToken";
?>