'Failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request - OAuth 2.0 POST

I am working with YouTube APIs for my college project, and I keep getting an error. Here I send them to the authorisation page to log in, when they allow access it sends the $_GET['code'] string back. Then I send this along with some other data and it should send back a JSON object. Instead I am just getting

Warning: file_get_contents(https://accounts.google.com/o/oauth2/token) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in http://www.example.net/callback.php on line 27

I have replaced my domain with example.net just for security

 urlencode($_GET['code']),
                'client_id' => urlencode('111522767640.apps.googleusercontent.com '),
                'client_secret' => urlencode('secret'),
                'redirect_uri' => urlencode('http://example.net/callback.php'),
                'grant_type' => urlencode('authorization_code')
            )
        );

        $params = 
        array('http' =>
            array(
                'method'  => 'POST /o/oauth2/token HTTP/1.1',
                'header'  => 'Host: accounts.google.com\r\n'.                           
                            'Content-Type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );

        $context = stream_context_create($params);
        $result = file_get_contents('https://accounts.google.com/o/oauth2/token', false,$context);
        var_dump($_SESSION);
        var_dump($result);
    }
    else //If code isnt set, user must have come here erroniously or has denied access to this program
    {
        //header( 'Location: www.example.net/error.php' ) ;
    }

?>


Solution 1:[1]

file_get_contents is going to make a GET request to the url specified, but oauth2/token needs a POST request.

See reference Google OAuth2, PHP HTTP.

Solution 2:[2]

if you are using oauth2, goto libraries/oauth2/provider.php and uncomment the code line 182 shows

            $ci = get_instance();
            $ci->load->spark('curl/1.2.1');
            $ci->curl
                ->create($url)
                ->post($params, array('failonerror' => false));

            $response = $ci->curl->execute();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Raveendra