when CURLOPT_HTTPHEADER need 'Content-Length' - php

I have this code in the client side of my application:
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length:0 ' )
);
$body = curl_exec($ch);
while in the server files:
$ch = curl_init($this->modelAddress);
$data = array("params"=>array("resource" => "artist","operation" => $operation,"params"=>$params));
$data_string = json_encode($data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
They are made from 2 different people and I want to ask what is the most correct.
When the use of 'Content-Length:0' instead of 'Content-Length:'.strlen($data_string) is better.
It's only question of POST/GET method?
I've searched explanations of this in the web but I've found nothing

If you use http PUT with curl then you have to specify the Content-Length header. Otherwise it is automatically handled by the curl for both GET and POST.
For example if you are posting the following data with curl with CURLOPT_POSTFIELDS. Then curl will automatically add the length of the data with the header.
$data = "name=alex&email=none!";
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
For better understand, run your curl code using verbose mode and you'll see how its handling the requests and responses.
curl_setopt($ch, CURLOPT_VERBOSE, true);

Related

Curl to test Sabre REST API Authentication Failing

I'm creating the authentication and getting an access token fine but the problem arises when I try to send a request. I'm creating the headers using PHP
<?php
define("POST", "POST");
**$environment=' https://api-crt.cert.havail.sabre.com';**
$userId='XXXXXXX';
$domain='AA';
$Group='XXXXXXXXXX';
$formatVersion='V1';
$clientSecret=base64_encode('XXXXXXXXXXX');
$client_id=base64_encode($formatVersion.":".$userId.":".$Group.":".$domain);
$bulid_credential=base64_encode($client_id.":".$clientSecret);
######################## Step 1: Get Token #############################
**$ch =curl_init("https://api-crt.cert.havail.sabre.com/v2/auth/token");**
$vars ="grant_type=client_credentials";
$header =array(
'Authorization: Basic '.$bulid_credential,
'Accept: */*',
'Content-Type: application/x-www-form-urlencoded'
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res= curl_exec($ch);
$result=json_decode($res);
$token=$result->access_token;
########################## Step 2: Call the REST API###################
**$url="https://api.test.sabre.com/v3.3.0/shop/flights?mode=live";**
$header = array(
'Authorization: Bearer'. $token,
'Content-Type: application/json'
);
$calltype='POST';
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $calltype);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonrequest);//Request
array_push($header, 'Content-Type: application/json');
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result=curl_exec($ch);
$result1=json_decode($result);
curl_close($ch);
?>
The Sabre Response :
{"status":"Incomplete","type":"Application","errorCode":"ERR.2SG.PROVIDER_ERROR","timeStamp":"2017-10-11T06:02:08.658-05:00","message":"Error occurred while invoking service rest:readMetadata:1.13.7.SNAPSHOT"}
1) Did you ensure that $token is a string and not an object?
I use this:
$result=json_decode($res, TRUE);
$token=$result['access_token'];
Instead of this:
$result=json_decode($res);
$token=$result->access_token;
2) Did you ensure that the content of $jsonrequest is valid?
Maybe it's not the PHP code that is incorrect, but your JSON query.

PHP POST to API with JSON Body and Auth

I am in the process of creating a super simple PHP page that sends JSON data to an remote API via POST. I am having issues with it and hoping someone here could help me out.
This is what I have so far
$url = "https://remoteHost.com/api/post";
$json = '{"message":"textHere", "user":"userABC"}';
$ch = curl_init();
$timeout = 0;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Basic --ACB123-ABC123---ABC123---',
'Content-Type: application/json',
'Content-Length: ' . strlen($json),)
);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
When I execute this nothing happens. The page loads without errors but it looks like the curl isn't actually doing anything. Any Ideas?

cURL HTTP Request with PHP (Routific API)

I'm trying to make an HTTP Request in PHP using cURL. The Request goes to the Routific (Route Optimization) API -> https://docs.routific.com/v1.3.1/docs
The idea is to send a JSON with different waypoints and get an optimal route back. Unfortunately, I get the following error when executing the code:
{"error":"Missing network"}
My Code looks as follows:
<?php
$data_string = json_encode(file_get_contents('Routes.json'));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.routific.com/v1/vrp");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: bearer API_KEY')
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
$result = curl_exec($ch);
echo $result;
curl_close($ch);
?>
What is wrong?
Thanks!

Put request using curl

after I succeeded in making a POST request and grab the values in the web service i'm building. I'm facing a problem regarding the Put Request. I managed to make the Put Request and I sent an array containing name and id for the update purpose this way:
curl_setopt($ic, CURLOPT_POSTFIELDS, http_build_query($data));
But when I try to grab the id sent using $_POST['id'] I get the undefined index error, I printed_r($_POST) and it's empty. Now I dont't believe there is a super global array for PUT like for POST and even if it exists , I don't think there is :
curl_setopt($ic, CURLOPT_PUTFIELDS, http_build_query($data));
in curl have you even been through a similar error? any idea?
To take a look at my previous post concerning the post request to have a better understanding of what I'm trying to do , it's here
Try this
curl_setopt($ic, CURLOPT_PUTFIELDS, json_encode($data));
and take it by
$array_get = json_decode(file_get_contents('php://input'));
use this CURLOPT_CUSTOMREQUEST =PUT and then just set values with CURLOPT_POSTFIELDS
or
you can use custom header CURLOPT_HTTPHEADER
eg.
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT'));
The script below demonstrates how you make a PUT request.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // note the PUT here
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)
));
// execute the request
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
The $_POST only for method=post;
You use method=put, so the $_POST is empty.
You can get the putdata like this:
$_PUT = array();
if('PUT' == $_SERVER['REQUEST_METHOD']){
parse_str(file_get_contents('php://input'), $_PUT);
}
This is the secret to sending a PUT request:
curl_setopt($ch, CURLOPT_POST, true); // <-- NOTE this is POST
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // <-- NOTE this is PUT
A full example:
$vals = array("email" => "hi#example.com", "phone" => "12345");
$jsonData = json_encode($vals);
curl_setopt($ch, CURLOPT_POST, true); // <-- NOTE this
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // <-- NOTE this
//We want the result / output returned.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type:application/json',
'Content-Length:' . strlen($jsonData),
'X-Apikey:Any_other_header_value_goes_here'
));
//Our fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
//Execute the request.
$response = curl_exec($ch);
echo $response;

PHP cURL GET request and request's body

i'm trying using cURL for a GET request like this:
function connect($id_user){
$ch = curl_init();
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
);
curl_setopt($ch, CURLOPT_URL, $this->service_url.'user/'.$id_user);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
$body = '{}';
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$authToken = curl_exec($ch);
return $authToken;
}
As you an see i want to pass $body as the request's body , but i don't know if its correct or not and i can't debug this actually, do you know if is the right to use curl_setopt($ch, CURLOPT_POSTFIELDS,$body); with a GET request?
Cause this enteire code works perfect with POST, now i'm trying change this to GET as you can see
The accepted answer is wrong. GET requests can indeed contain a body. This is the solution implemented by WordPress, as an example:
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $body );
EDIT: To clarify, the initial curl_setopt is necessary in this instance, because libcurl will default the HTTP method to POST when using CURLOPT_POSTFIELDS (see documentation).
CURLOPT_POSTFIELDS as the name suggests, is for the body (payload) of a POST request. For GET requests, the payload is part of the URL in the form of a query string.
In your case, you need to construct the URL with the arguments you need to send (if any), and remove the other options to cURL.
curl_setopt($ch, CURLOPT_URL, $this->service_url.'user/'.$id_user);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
//$body = '{}';
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
//curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
<?php
$post = ['batch_id'=> "2"];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://example.com/student_list.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
$result = json_decode($response);
curl_close($ch); // Close the connection
$new= $result->status;
if( $new =="1")
{
echo "<script>alert('Student list')</script>";
}
else
{
echo "<script>alert('Not Removed')</script>";
}
?>
For those coming to this with similar problems, this request library allows you to make external http requests seemlessly within your php application. Simplified GET, POST, PATCH, DELETE and PUT requests.
A sample request would be as below
use Libraries\Request;
$data = [
'samplekey' => 'value',
'otherkey' => 'othervalue'
];
$headers = [
'Content-Type' => 'application/json',
'Content-Length' => sizeof($data)
];
$response = Request::post('https://example.com', $data, $headers);
// the $response variable contains response from the request
Documentation for the same can be found in the project's README.md
you have done it the correct way using
curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
but i notice your missing
curl_setopt($ch, CURLOPT_POST,1);

Categories