Below is an example without CURLOPT_HTTPHEADER, and it works fine.
<?php
$URL = "http://someurl.info";
$data = 'x_test_request=0&x_version=3.1&x_delim_data=true&x_relay_response=false';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 1800);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
?>
Does Curl auto-detect the type of data we Post, and auto-count the string length?
Or should we always specify Both?
Or does it largely depend on the destination's rules and expectations?
To be safe, I usually add the header info like this:
<?php
$contentlen = strlen(trim($data));
$headersARR = array(
"Content-type: application/x-www-form-urlencoded",
"Content-length: ".$contentlen,
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headersARR);
?>
I read http://us1.php.net/curl_setopt, but haven't noticed any details on defaulted content-type parameters.
If you do not specify anything about Content-type but use the CURLOPT_POSTFIELDS then the header is always Content-type: application/x-www-form-urlencoded as default. Also it sets the Content-length: automatically.
For this reason, when we post JSON content through the POST we need to override the content-type through HTTPHEADER option. It is similar to XML or any other specific type of content.
Related
I try to send a post request to another php page with the following code:
$vars = ['val1' => 'myval'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_MAXREDIRS, 4);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_USERPWD, "username:password");
$data = curl_exec($ch);
curl_close($ch);
But on the target page, var_dump($_POST); will output only "1". I had expected something like:
array(val1 = myval) or something similar. So that i can check with isset($_POST["val1"]) if this exists and contains "myval".
Any ideas whats wrong with the request?
Edit:
I have now changed my code to the following:
<?php
$data = array(
'foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
$ch=curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_URL, "target.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
And in target.php:
<?php
echo print_r($_POST, true));
?>
But there is no response. Both files are in the same dir at the server.
That's because curl_setopt() doesn't accept such complext types as array ;) You need to present your data in form of a query string: "postvar1=value1&postvar2=value2&postvar3=value3".
$format = http_build_query($vars);
curl_setopt($ch, CURLOPT_POSTFIELDS, $format);
or
$format = "val1=my-value"; // be careful to create proper encoding
curl_setopt($ch, CURLOPT_POSTFIELDS, $format);
If you're using CURLOPT_POSTFIELDS, you don't need to set CURLOPT_POST as well. In fact, setting it after will result in a potentially incorrect header being sent.
CURLOPT_POSTFIELDS accepts an array, and will set the Content-Type header to multipart/form-data if one is provided. Later, setting CURLOPT_POST will overwrite this to application/x-www-form-urlencoded, and means that the PHP script at the other end will expect data encoded as an HTTP query-string. This is why you're having problems.
You can fix this either by encoding $vars correctly before sending (using http_build_query, as in the other answer), or just remove the call to set CURLOPT_POST. I'd recommend the latter.
I think, i got it. When i set as target something like "target.php", data was not send. But when i use a complete URL, like https://myserver.com/target.php, this will work as expected. Sometimes, its to easy... sorry for stealing your time.
I'm trying to submit a POST request with JSON data to an api endpoint. The endpoint requires a querystring passing the api credentials, but also requires the JSON data to be POSTed.
When I try to do this with PHP cURL as shown below, the querystring is apparently removed - thus the api is rejecting the request due to missing api key.
I can do this easily with Postman when testing access to the api endpoint.
How can I make the cURL request include both the querystring AND the JSON POST body?
Example code:
// $data is previously defined as an array of parameters and values.
$url = "https://api.endpoint.url?api_key=1234567890";
$ch = curl_init();
$json = json_encode($data);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($json)
]
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
You are doing almost right.
Sometimes you need to relax SSL verification.
Otherwise, update php ca bundle:
https://docs.bolt.cm/3.7/howto/curl-ca-certificates
Add the following:
$headers = array(
"Content-type: application/json;charset=UTF-8",
"Accept-Encoding: gzip,deflate",
"Content-length: ".strlen($json),
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 300);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_ENCODING, "identity, deflate, gzip");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
Sometimes you need to change encoding too:
$result = utf8_decode($result);
And check the returning data.
I'm hoping someone can help me. I'm sending an API request, via CURL, using PHP. The headers to the third party application need to be as follows:
$headers = array(
"content-type: application/json",
"Accept: application/json"
);
The CURL request is initialised and sent as follows:
// 1. initialize
$ch = curl_init();
// 2. set the options, including the url
curl_setopt($ch, CURLOPT_URL, $this->sendPropertyUrl);
curl_setopt($ch, CURLOPT_HEADER, $headers);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSLCERT, $this->certPath);
curl_setopt($ch, CURLOPT_CAINFO, $this->certPath);
curl_setopt($ch, CURLOPT_SSLKEYPASSWD, $this->certPassword);
curl_setopt($ch, CURLOPT_POSTFIELDS, $propertyDataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 3. execute and fetch the resulting HTML output
$rightmoveResponse = curl_exec($ch);
$output = json_decode($rightmoveResponse, true);
However if I trap the header info actually sent in the CURL request the output is as follows:
POST /v1/property/sendpropertydetails HTTP/1.1
Host: adfapi.adftest.rightmove.com
Accept: */*
Content-Length: 1351
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue
Can anyone explain why CURL has modified the Accept and Content-Type parameters?
Any help greatly appreciated.
Brian
What you want is defined by CURLOPT_HTTPHEADER instead of CURLOPT_HEADER.
From PHP Docs:
CURLOPT_HEADER TRUE to include the header in the output.
CURLOPT_HTTPHEADER An array of HTTP header fields to set, in the format array('Content-type: text/plain', 'Content-length: 100')
See this user note about using it.
You used curl_setopt($ch, CURLOPT_POST, true); which sets the content-type. Instead use curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); (see http://php.net/manual/en/function.curl-setopt.php).
This is in addition to what #Alan Machado said.
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);
Objective:
I want to send multiple images using multipart/form-data. Below is a snippet of my code.
Problem:
On one PC, the multipart attachment is sent by the correct MIME header Content-Type: image/jpeg, but on another PC, the MIME header is Content-Type: application/octet.
Question:
How can I force cURL to set the correct Content-Type header for the MIME content?
$ch = curl_init();
$params = array('name' => '#D:\globe.jpg');
$base_url = "https://example.com"."?".varEncode($test_data);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_URL,$base_url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
Use the CURLOPT_HTTPHEADER option:
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: image/jpeg"));
So specify Content-Type headers specifically for file uploads, use:
$params = array('name'=>'#D:\globe.jpg;type=image/jpeg');
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);