Php Curl already set authorization but wont work?


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) :


use chriskacerguisRestServerRestController;

require APPPATH . 'libraries/RestController.php';

class Api_S extends RestController
    public function index()

    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_POSTFIELDS => 'start=2&limit=10',
            CURLOPT_USERPWD => $username . ":" . $password,
            CURLOPT_HEADER => true,
            CURLOPT_HTTPHEADER => array(
                'api_auth_key: xxx',
                'Authorization: Basic xxx',
                'Content-Type: application/x-www-form-urlencoded'

        $response = curl_exec($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?


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?