Search code examples
phpwordpresswordpress-rest-api

WordPress JSON API AUTH with PHP Curl


I am working with wordpress and using this plugin https://wordpress.org/plugins/json-api-auth/ for JSON API Auth and I am trying to return success with curl in PHP but whenever I run the code I am getting {"status":"error","error":"Invalid username and\/or password."}

<?php
    $curl = curl_init();
    
    curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://example.com/api/auth/generate_auth_cookie/?username="abcd"&password="abcd"',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    ));
    
    $response = curl_exec($curl);
    
    curl_close($curl);
    echo $response;
?>

But when I put this in the browser url https://example.com/api/auth/generate_auth_cookie/?username=abcd&password=abcd I am getting success {"status":"ok","cookie":"xyz","cookie_name":"xyzxyz","user":{"id":1,"username":"abcd","nicename":"abcd","email":"abcd@abcd.com","url":"","registered":"2020-09-10 10:42:41","displayname":"abcd","firstname":"abcd","lastname":"abcd","nickname":"abcd","description":"","capabilities":{"administrator":true},"avatar":null}}

Can you help me what I am doing wrong with curl in PHP?

Original version of CURLOPT_URL that I have used in code

CURLOPT_URL => 'https://example.com/api/auth/generate_auth_cookie/?username="'.$this->input->post('email').'"&password="'.$this->input->post('password').'"',

Solution

  • Remove the " from the cURL url query string. The WordPress PHP handling your request would read your username as "abcd" instead of abcd as you are trying to achieve.

    CURLOPT_URL => 'https://example.com/api/auth/generate_auth_cookie/?username="abcd"&password="abcd"'
    

    Should be

    CURLOPT_URL => 'https://example.com/api/auth/generate_auth_cookie/?username=abcd&password=abcd'