Php Curl already set authorization but wont work?

Issue

This Content is from Stack Overflow. Question asked by Muhammad Fauzi

I am on a work project using Codeigniter 3. I am trying to hit php restful api with basic authentication using this code generated from postman(already tested in postman and it works) :

<?php

use chriskacerguisRestServerRestController;

require APPPATH . 'libraries/RestController.php';


class Api_S extends RestController
{
    public function index()
    {
        parent::__construct();
    }

    public function get_dp()
    {
        $curl = curl_init();
        $username = "xxx";
        $password = "xxx";
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://xxx',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => 'start=2&limit=10',
            CURLOPT_USERPWD => $username . ":" . $password,
            CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
            CURLOPT_HEADER => true,
            CURLOPT_HTTPHEADER => array(
                'api_auth_key: xxx',
                'Authorization: Basic xxx',
                'Content-Type: application/x-www-form-urlencoded'
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        echo $response;
    }
}

But whenever i try to redirect to call the function get_dp() in Api_S controller the browser shows alert which ask username and password, but i already defined the username, password and the token in php curl code above. Even when i input it in the alert input field and clicked sign in it wont do anything. What i expect is when i redirect to call the function in api controller it will simply run the function (it will echo the api response) without asking for authorization again since i already include it in the php curl code above. What did i do wrong?How do i achieve that?



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?