Call one controller function from another using Curl PHP in CodeIgniter 3

142 Views Asked by At

Hi I am using Curl PHP to callone controller from Another but even after passing CSRF it is giving me 403 error

MAIN controller file `

<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Main extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
    }
    
    public function checkAjax()
    {
        $curl = curl_init();
        print_r(http_build_query([
            $this->security->get_csrf_token_name() => $this->security->get_csrf_hash(),
            'number' => 3
        ]));
        curl_setopt_array($curl, [
            CURLOPT_PORT => "8080",
            CURLOPT_URL => "http://localhost:8080/ci/ajax",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POST, true,
            CURLOPT_POSTFIELDS => http_build_query([
                $this->security->get_csrf_token_name() => $this->security->get_csrf_hash(),
                'number' => 3
            ])
        ]);
        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            echo "cURL Error #:" . $err;
        } else {

            echo ($httpcode >= 400) ? "Enough" : htmlspecialchars($response);
        }
    }
}

`

The Controller I am calling

your text

<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Ajax extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
    }
    public function index()
    {
        print_r($this->input->post());
        exit(json_encode(($_POST['number'] == 3) ? ['hello' => 298] :  ['bye' => 171]));
    }
}

Without CSRF working fine but cannot remove CSRF token.

Please recommend the solutions Because I need it get resolved.

I was expecting it to work fine

0

There are 0 best solutions below