Home > Software design >  curl gives 400 error but works in postman?
curl gives 400 error but works in postman?

Time:07-01

I am using codeigniter-3 ,inside controller i am hitting one external API it's giving 400 error but same curl request if i hit in postman it's working fine can you please help me did i miss anything ..?

CURL REQUEST in postman

curl --location --request POST 'http://armycalling.com/baligaz-api/api/userapi/login' \
--header 'x-api-key: ccccc' \
--header 'Authorization: Basic YWRtaW46YmFsaWdheiFAIyQ=' \
--header 'Content-Type: application/json' \
--header 'Cookie: ci_session=f3630b226e539f4aa079e980e23cc730609a1627' \
--data-raw '{
    "email" : "[email protected]",
    "password" : "dummy.srk"
}'

usercontroller.php

if(isset($_POST['login']))
        {
            //phpinfo();
            $url = 'http://localhost/login';
            $u_name = $this->input->post('username');
            $password= $this->input->post('password');
            $curl = curl_init($url);
            $data = [
                'email'=>$u_name, 
                'password'=>$password
            ];
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                        'x-api-key: ccccc',
                        'Authorization: Basic YWRtaW46YmFsaWdheiFAIyQ=',
                        'Content-Type: Application/json',
                        'Cookie: ci_session=6dc4b8f72e2953c590ff503bd47f52ecfa158c79'
            ));
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            $result = curl_exec($curl);
            $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            return print($httpcode);
            curl_close($curl);

CodePudding user response:

Setting this request to use a cookie session and sending the username/password in a POST request yields a successful login.

function curl( $url=NULL, $options=NULL, $headers=false ){
    $vbh = fopen('php://temp', 'w ');
    session_write_close();

    /* Initialise curl request object - these should be OK as-is */
    $curl=curl_init();

    /* Define standard options */
    curl_setopt( $curl, CURLOPT_URL, trim( $url ) );
    curl_setopt( $curl, CURLOPT_AUTOREFERER, true );
    curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
    curl_setopt( $curl, CURLOPT_FAILONERROR, true );
    curl_setopt( $curl, CURLOPT_HEADER, false );
    curl_setopt( $curl, CURLINFO_HEADER_OUT, false );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $curl, CURLOPT_BINARYTRANSFER, true );
    curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 20 );
    curl_setopt( $curl, CURLOPT_TIMEOUT, 60 );
    curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0' );
    curl_setopt( $curl, CURLOPT_MAXREDIRS, 10 );
    curl_setopt( $curl, CURLOPT_ENCODING, '' );
    
    /* enhanced debug */
    curl_setopt( $curl, CURLOPT_VERBOSE, true );
    curl_setopt( $curl, CURLOPT_NOPROGRESS, true );
    curl_setopt( $curl, CURLOPT_STDERR, $vbh );
    

    /* Assign runtime parameters as options to override defaults if needed. */
    if( isset( $options ) && is_array( $options ) ){
        foreach( $options as $param => $value ) curl_setopt( $curl, $param, $value );
    }
    
    /* send any headers with the request that are needed */
    if( isset( $headers ) && is_array( $headers ) ){
        curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );
    }

    /* Execute the request and store responses */
    $res=(object)array(
        'response'  =>  curl_exec( $curl ),
        'status'    =>  curl_getinfo( $curl, CURLINFO_RESPONSE_CODE ),
        'info'      =>  (object)curl_getinfo( $curl ),
        'errors'    =>  curl_error( $curl )
    );
    
    rewind( $vbh );
    $res->verbose=stream_get_contents( $vbh );
    fclose( $vbh );
    curl_close( $curl );
    
    return $res;
}


# create a temporary file somewhere to store cookie data.
# Using the system temp directory should mean automatic 
# deletion of these files in time.
$cookiestore=tempnam( sys_get_temp_dir(), '_cookiejar_' );


$url='http://armycalling.com/baligaz-api/api/userapi/login';


$headers=array(
    'x-api-key: BALIGAZ@123',
    'Authorization: Basic YWRtaW46YmFsaWdheiFAIyQ='
);

$args=array(
    'email'     =>  '[email protected]',
    'password'  =>  'rasakumar.srk'
);

/*
    Mark the request as a new Cookie session - subsequent requests
    would have different options without CURLOPT_COOKIESESSION
*/
$options=array(
    CURLOPT_COOKIESESSION   =>  true,
    CURLOPT_COOKIEFILE      =>  $cookiestore,
    CURLOPT_COOKIEJAR       =>  $cookiestore,
    CURLOPT_POST            =>  true,
    CURLOPT_POSTFIELDS      =>  $args
);      

/* 
    Make the request with specified config options
*/
$res=curl( $url, $options, $headers );

/* 
    If the request is successful a 200 OK status code will be received
    so we can then proceed to work with the response data.
    
    If the request fails, using the returned info & verbose properties
    of the response will show useful debug info.
*/
if( $res->status==200 ){
    printf('<pre>%s</pre>',print_r( $res->response, true ) );
}

This yields:

{
  "status": true,
  "message": "User login successful.",
  "data": {
    "id": "22",
    "user_id": "baligaz_595689",
    "first_name": "Rasa",
    "last_name": "Kumar",
    "email": "[email protected]",
    "password": "529f263ebb230b4709003bb0f7457f90",
    "phone": "73339190384",
    "profile_img": "http://armycalling.com/baligaz-api/profile_image/baligaz_595689_app_one.png",
    "role": "1",
    "station_id": "HP Petrols",
    "forgot_otp": "",
    "created": "2022-06-24 04:47:13",
    "created_by": null,
    "modified": "2022-06-30 23:38:15",
    "updated_by": "baligaz_595689",
    "login_completed": null,
    "status": "1"
  }
}
  • Related