phpcodeignitercurltankauth

Google Login Failed, Failed to open stream Http request failed and Bad Request


How to change file_get_contents() to curl funtion

Error occured in this below lines like.

Fatal error: Uncaught exception 'Exception' with message 'Required option not passed: access_token ' in E:\xampp\htdocs\google\application\libraries\oauth2\Token\Access.php:44 Stack trace: #0 E:\xampp\htdocs\google\application\libraries\oauth2\Token.php(30): OAuth2_Token_Access->__construct(NULL) #1 E:\xampp\htdocs\google\application\libraries\oauth2\Provider.php(224): OAuth2_Token::factory('access', NULL) #2 E:\xampp\htdocs\google\application\libraries\oauth2\Provider\Google.php(61): OAuth2_Provider->access('4/tJi51U-xhCSYo...', Array) #3 E:\xampp\htdocs\google\application\controllers\auth_oa2.php(32): OAuth2_Provider_Google->access('4/tJi51U-xhCSYo...') #4 [internal function]: Auth_oa2->session('google') ...

    $opts = array(
                'http' => array(
                    'method'  => 'POST',
                    'header'  => 'Content-type: application/x-www-form-urlencoded',
                    'content' => http_build_query($params),
                )
            );

            $_default_opts = stream_context_get_params(stream_context_get_default());
            $context = stream_context_create(array_merge_recursive($_default_opts['options'], $opts));
            $response = file_get_contents($url, false, $context);

            $return = json_decode($response, true);

Solution

  • using curl,

    $opts = array(
                    'http' => array(
                        'method'  => 'POST',
                        'header'  => 'Content-type: application/x-www-form-urlencoded',
                        'content' => http_build_query($params),
                    )
                );
    
                $_default_opts = stream_context_get_params(stream_context_get_default());
                $context = stream_context_create(array_merge_recursive($_default_opts['options'], $opts));
    

    Instead of above code use this,

    $_default_opts = stream_context_get_params(stream_context_get_default());
    $context = array_merge($_default_opts['options'], $params);
    
             $curl = curl_init();
            curl_setopt($curl, CURLOPT_HEADER, false);
            curl_setopt($curl, CURLINFO_HEADER_OUT, true);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_FORBID_REUSE, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($context));
    
            $response = curl_exec($curl);
            curl_close($curl);