I have this code
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("'Content-Type: application/json; charset=utf-8'"));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data_str));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$xmlresult = curl_exec($ch);
$xmlError = $xmlresult;
$json = json_decode($xmlresult, true);
The answer I get into json but I could not convert because the in the beginning answer is, extra characters See example
п»ї{"customerPaymentProfileIdList":[],"customerShippingAddressIdList":[],"validationDirectResponseList":[],"messages":{"resultCode":"Error","message":[{"code":"E00039","text":"A duplicate record with ID 39223758 already exists."}]}}
response header
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 232
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 2.0.50727
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: PUT,OPTIONS,POST,GET
Access-Control-Allow-Headers: x-requested-with,cache-control,content-type,origin,method,SOAPAction
Date: Thu, 04 Feb 2016 09:08:15 GMT
Connection: keep-alive
Because of the extra characters I can not json_decode string. What can be done?
I encountered the same issue when developing my library for accessing their JSON API. In the code that handles the response I had to strip those characters out in order to properly decode the string as JSON.
Line 113:
$this->responseJson = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $responseJson);
I'm having the same issue in Node.js with JSON.parse().
var https = require('https');
var requestData = {
"getCustomerProfileIdsRequest": {
"merchantAuthentication": {
"name": "your-auth-name-here",
"transactionKey": "your-trans-key-name-here"
}
}
};
var requestString = JSON.stringify(requestData);
var req = https.request({
host: "apitest.authorize.net",
port: "443",
path: "/xml/v1/request.api",
method: "POST",
headers: {
"Content-Length": requestString.length,
"Content-Type": "application/json"
}
});
req.on('response', function (resp) {
var response = '';
resp.setEncoding('utf8');
resp.on('data', function(chunk) {
response += chunk;
});
resp.on('end', function() {
var buf = new Buffer(response);
console.log('buf[0]:', buf[0]); // 239 Binary 11101111
console.log('buf[0] char:', String.fromCharCode(buf[0])); // "ï"
console.log('buf[1]:', buf[1]); // 187 Binary 10111011
console.log('buf[1] char:', String.fromCharCode(buf[1])); // "»"
console.log('buf[2]:', buf[2]); // 191 Binary 10111111
console.log('buf[2] char:', String.fromCharCode(buf[2])); // "¿"
console.log('buf[3]:', buf[3]); // 123
console.log('buf[3] char:', String.fromCharCode(buf[3])); // "{"
// Note: The first three chars are a "Byte Order Marker" i.e. `BOM`, `ZERO WIDTH NO-BREAK SPACE`, `11101111 10111011 10111111`
response = JSON.parse(response); // Throws error: 'Unrecoverable exception. Unexpected token SyntaxError: Unexpected token'
console.log(response);
});
});
req.on('error', function (error) {
console.log(JSON.stringify(error));
});
req.on('socket', function(socket) {
socket.on('secureConnect', function() {
req.write(requestString);
req.end();
});
});
If I call trim() on the response, it works:
response = JSON.parse(response.trim());
Or replace the BOM:
response = response.replace(/^\uFEFF/, '');
response = JSON.parse(response);
Related
I am calling a REST service using php curl. If an error occurs (for example because I posted invalid data) the REST server returns error code 400 and provides informative application error details in the response header custom field.
However, when error 400 occurs the header is not provided in the result from curl_exec() at it returns FALSE even though setopt as been provided. Headers are seen if code returned is 2xx.
curl_setopt($curl,CURLOPT_HEADER, 1);
Is there any way to get the response headers on errors >= 400?
In the example below, I'm using https://httpstat.us/400 to simulate a HTTP 400 response code.
<?php
// create curl resource
$ch = curl_init();
// set url that responds with HTTP 400 status
curl_setopt($ch, CURLOPT_URL, "https://httpstat.us/400");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//enable headers
curl_setopt($ch, CURLOPT_HEADER, 1);
//get only headers
curl_setopt($ch, CURLOPT_NOBODY, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
$headers = [];
$output = rtrim($output);
$data = explode("\n",$output);
$headers['status'] = $data[0];
array_shift($data);
foreach($data as $part){
//some headers will contain ":" character (Location for example), and the part after ":" will be lost, Thanks to #Emanuele
$middle = explode(":",$part,2);
//Supress warning message if $middle[1] does not exist, Thanks to #crayons
if ( !isset($middle[1]) ) { $middle[1] = null; }
$headers[trim($middle[0])] = trim($middle[1]);
}
// Print all headers as array
print_r($headers);
This returns
Array
(
[status] => HTTP/1.1 400 Bad Request
[Cache-Control] => private
[Content-Length] => 15
[Content-Type] => text/plain; charset=utf-8
[Server] => Microsoft-IIS/10.0
[X-AspNetMvc-Version] => 5.1
[Access-Control-Allow-Origin] => *
[X-AspNet-Version] => 4.0.30319
[X-Powered-By] => ASP.NET
[Set-Cookie] => ARRAffinity=93fdbab9d364704de8ef77182b4d13811344b7dd1ec45d3a9682bbd6fa154ead;Path=/;HttpOnly;Domain=httpstat.us
[Date] => Wed, 13 Nov 2019 23:31:51 GMT
)
That array with all response headers matches up with what I get when I use curl from my terminal:
curl -v https://httpstat.us/400
returns
< HTTP/1.1 400 Bad Request
< Cache-Control: private
< Content-Length: 15
< Content-Type: text/plain; charset=utf-8
< Server: Microsoft-IIS/10.0
< X-AspNetMvc-Version: 5.1
< Access-Control-Allow-Origin: *
< X-AspNet-Version: 4.0.30319
< X-Powered-By: ASP.NET
< Set-Cookie: ARRAffinity=93fdbab9d364704de8ef77182b4d13811344b7dd1ec45d3a9682bbd6fa154ead;Path=/;HttpOnly;Domain=httpstat.us
< Date: Wed, 13 Nov 2019 23:33:19 GMT
Here's another option using the CURLOPT_HEADERFUNCTION option with a callback function:
<?php
// this holds the response headers from the curl call
$responseHeaders = array();
// this function processes the response headers from the curl call
function curlResponseHeaderCallback($ch, $headerLine) {
global $responseHeaders;
// trim all the whitespace on this line
$trimmed = trim($headerLine);
// only proceed if the string is not empty
if(!empty($trimmed)) {
// headers follow Key: Value format
$split = explode(':', $trimmed);
// only proceed if the value of the header is not empty
if(!empty($split[1])) {
// $split[0] is the Key of the response header
// $split[1] is the Value of the response header, which can also have whitespace
$responseHeaders[$split[0]] = trim($split[1]);
}
}
// who knows why, but you have to return this.
return strlen($headerLine);
}
// get cURL resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "https://httpstat.us/400");
curl_setopt($ch, CURLOPT_HEADERFUNCTION, "curlResponseHeaderCallback");
// send the request
curl_exec($ch);
// close the handle
curl_close($ch);
print_r($responseHeaders);
returns
Array
(
[Cache-Control] => private
[Content-Length] => 15
[Content-Type] => text/plain; charset=utf-8
[Server] => Microsoft-IIS/10.0
[X-AspNetMvc-Version] => 5.1
[Access-Control-Allow-Origin] => *
[X-AspNet-Version] => 4.0.30319
[X-Powered-By] => ASP.NET
[Set-Cookie] => ARRAffinity=93fdbab9d364704de8ef77182b4d13811344b7dd1ec45d3a9682bbd6fa154ead;Path=/;HttpOnly;Domain=httpstat.us
[Date] => Wed, 13 Nov 2019 23
)
I am trying to update workspace name through geoserver rest api using put method.
I am getting "Can't change the name of a workspace." error.
This is my code.
$service = geoserver_url;
$data = "<workspace><name>testnew</name></workspace>";
$url = $service . "rest/workspaces/workspacename";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$passwordStr = username:password
curl_setopt($ch, CURLOPT_USERPWD, $passwordStr);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/xml"););
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
Any kind of help appreciated.
That is not an allowable operation (as mentioned in the manual). Any PUT that changes the name of a workspace returns a 403 Error.
All you can do is create a new workspace, copy the contents of the old one and then delete it.
According to geoserver REST API documentations (link), you can simply edit workspace name (ws_name) by putting a request which has an xml string data in its body.
Here I've given you an example. Because of using Express as my application sever I've implemented a request using javascript but it can be changed to your favorite syntax.
const options = {
url: 'http://localhost:8080/geoserver/rest/workspaces/{current_ws_sname}',
method: 'PUT',
headers: { 'Content-type': 'text/xml' },
body: '<workspace><name>{new_ws_name}</name></workspace>',
auth: {
user: {geoserver_username},
pass: {geoserver_password}
}
and for executing the request based on above option variable I've used request function in Express:
request(options, (error, response, body) => {
console.log('response status code:' , response.statusCode)
console.log('response status message: ', response.statusMessage)
const result = {}
if (!error) {
const statusCode = response.statusCode;
const statusMessage = response.statusMessage;
if (statusCode == 200) {
result.err = false
result.msg = `Modified`
} else if (statusCode == 404) {
result.err = true
result.msg = 'Workspace not found!'
} else if (statusCode == 405) {
result.err = true
result.msg = 'Forbidden to change the name of the workspace!'
//because of your username and/or password
} else if (statusCode == 500) {
result.err = true
result.msg = 'Server internal error or duplicate names'
}
} else {
result.err = true,
result.msg = error;
}
res.send(result);
})
Don't forget to replace {current_ws_sname}, {new_ws_sname}, {geoserver_username}, {geoserver_password} by your own values.
All the possible situations have been mentioned as above (i.e. 200, 404, 405, 500) and there is no error message like "Can't change the name of a workspace." in geoserver documentations!
What statusCode and statusMessage do you get in response? Can you confirm that your {new_ws_sname} isn't duplicate?
My curl exec response returns this:
string(151937) "HTTP/1.1 200 OK Access-Control-Allow-Headers: Content-Type, Accept-Tenant, Authorization Access-Control-Allow-Methods: POST,GET,PUT,PATCH,OPTIONS Access-Control-Allow-Origin: * Cache-Control: private Content-Type: application/json; charset=utf-8 Date: Mon, 28 Sep 2015 08:35:33 GMT Server: Microsoft-IIS/7.5 Warning: Unsupported Authentication Scheme X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Content-Length: 151475 Connection: keep-alive {"ShortResultText":"SE19","Restaurants":[{"Id":50371,"Name":"Mahjestics Caribbean Cuisine","Address":"247 Gypsy Road","Postcode":"SE27 9QY","City":"London","CuisineTypes":[{"Id":76,"Name":"Caribbean","SeoName":null},{"Id":97,"Name":"African","SeoName":null}],"Url":"http://majestic-caribbean-cuisine-west-norwood.just- ...
But the JSON starts here at "{ ShortResultText"..:
{
"ShortResultText": "SE19",
"Restaurants": [
{
"Id": 50371,
"Name": "Mahjestics Caribbean Cuisine",
"Address": "247 Gypsy Road",
"Postcode": "SE27 9QY",
"City": "London",
"CuisineTypes": [
{
"Id": 76,
"Name": "Caribbean",
"SeoName": null
},
{
"Id": 97,
"Name": "African",
"SeoName": null
}
"Url": "http://majestic-caribbean-cuisine-west-norwood.test.co.uk",
"IsOpenNow": true,
"IsSponsored": false,
"IsNew": false,
"IsTemporarilyOffline": false,
"ReasonWhyTemporarilyOffline": "",
"UniqueName": "majestic-caribbean-cuisine-west-norwood",
"IsCloseBy": false,
"IsHalal": true,
"DefaultDisplayRank": 1,
"IsOpenNowForDelivery": true,
"IsOpenNowForCollection": true,
"RatingStars": 4.71,
"Logo": [
{
"StandardResolutionURL": "http://d30v2pzvrfyzpo.cloudfront.net/uk/images/restaurants/50371.gif"
}
],
"Deals": [],
"NumberOfRatings": 7
I need to get JUST the JSON data from my curl response and I'm not sure the best way to go about it? The curl response header might vary in length depending on the "ShortResultText" value from POST as this is a variable.
Then I'll be able to get the data in an array and loop through it.
Curl code:
$url = "http://api-interview.test.com/restaurants?q=se19";
$ch = curl_init();
$api_headers = array(
'Content-Type: text/plain; charset=utf-8',
'Accept-Tenant: uk',
'Accept-Language: en-GB',
'Authorization: Basic VGVjaFRlc3RBUEk6dXNlcjI=',
'Host: api-interview.test.com'
);
//print_r($api_headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $api_headers);
// echo "<pre>";
// $data = curl_exec($ch);
// echo "</pre>";
echo "<pre>";
$data = curl_exec($ch);
echo "</pre>";
//just testing here
// $json = json_encode($data, true);
// $json1 = json_decode($json, true);
// var_dump($json1);
//print $json1['restaurants'];
//$json = json_encode($data, true);
// foreach($json['restaurants'] as $value) {
// echo $value->postcode;
// }
curl_close($ch);
You only have to set CURLOPT_HEADER to false.
Try this:
$json1 = json_decode($json, true);
foreach($json1['Restaurants'] as $key => $val){
print_r($val); // You will get here the ID, Name ....
echo 'ID: ' $val['Id'] . 'Name: ' . $val['Name']; . 'Rating Stars: ' . $val['RatingStars']..
//If you want to go deeper and get the CuisineTypes just do below
foreach($val['CuisineTypes'] as $key2 => $val2) {
print_r($val2); //This is the cuisine types
}
}
Or you can just manipulate your array:
$newData = [];
foreach($json1['Restaurants'] as $key => $val)
{
$newData[] = ['Name' => $val['Name'], 'CusineTypes' => $val['CuisineTypes'], 'RatingStars' => $val['RatingStars']];
}
print_r($newData);
I don't know what I'm doing wrong but I've already lost a couple days struggling with this.
Here is my cURL request from the command line:
curl -i -H "Accept: text/html" http://laravel.project/api/v1/users/4
This returns:
HTTP/1.1 200 OK
Server: nginx/1.6.2
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: no-cache
Date: Sun, 29 Mar 2015 10:33:36 GMT
Set-Cookie: laravel_session=eyJpdiI6ImNPTkZIYVJZSVRKaHBOZTR3SWh0dHc9PSIsInZhbHVlIjoiblpZYVJlN2dBY1ljejNIYUQycXpsNXRWd1I5a3JSRG8wSWdDOWlHVTMrYUcrdDBNVmVuZUNkOGtJb2M4bXFpTFF3cUdoTFZOVXBWXC82Q1luSGd5bjJBPT0iLCJtYWMiOiI0ZTEwOWQxMmVhMzY2NjI1Yzc1MTBmZmRmYjUyOGQwNDlhYzRjOTNiM2FiOWIyN2E1YjA0OTM4YTUxZmNmMzMzIn0%3D; expires=Sun, 29-Mar-2015 12:33:36 GMT; Max-Age=7200; path=/; httponly
{
"data":{
"id":4,
"name":"Helena",
"email":"hh#gmail.com",
"created_at":"2015-03-26 21:13:16",
"updated_at":"2015-03-26 21:13:16"
}
}
So everything looks fine: the Content-type is correctly set and response is in JSON.
But now watch what happens if I consume the API with curl in PHP:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $final_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
$result = curl_exec($ch);
return json_decode($result);
I get this response:
{#165
+"data": {#167
+"id": 4
+"name": "Helena"
+"email": "hh#gmail.com"
+"created_at": "2015-03-26 21:13:16"
+"updated_at": "2015-03-26 21:13:16"
}
}
And, if I return the $result without json_decode, I get this:
"{
"data":{
"id":4,
"name":"Helena",
"email":"hh#gmail.com",
"created_at":"2015-03-26 21:13:16",
"updated_at":"2015-03-26 21:13:16"
}
}"
The correct response but inside quotes. I've read in PHP docs that curl_opt_returntranfer returns the result as a string but I can't be the only person on the planet that just wants to get the JSON.
This is my ApiController class:
class ApiController extends Controller {
// Base controller for API Controllers
protected $statusCode = 200;
protected function respond($data)
{
return Response::json([
'data' => $data,
]);
}
protected function respondNotFound($message = 'No data found')
{
return Response::json([
'error' => [
'message' => $message,
'status_code' => $this->getStatusCode(),
]
]);
}
}
This is my UserController:
class UserController extends ApiController {
public function show($user)
{
if ($user == null)
return $this->setStatusCode(404)->respondNotFound('User not found');
return $this->respond($user);
}
}
And if I return the $result without json_decode i get this: The correct response but inside quotes
nope, what makes you think that? i guess the problem is how you are printing it, you are most likely printing it with var_export($result) or var_dump($result) or echo json_encode($result); which is adding the quotes. if you just want the json, just echo it with echo $result;, no extra processing, just echo the string as-is, it's already json.
I think this will solve your problem:
curl -i -H "Accept: text/html" http://laravel.project/api/v1/users/4 | tr -d '"'
$response = (string)$result;
$resp_arr = explode("<!DOCTYPE",$response);
$obj = json_decode(trim($japi_arr[0]));
if(isset($obj[0]))
{
$rsp_id = $obj[0]->id;
$rsp_name = $obj[0]->name;
I'm calling a service from PHP using cURL, like this:
$response = curl_exec($ch);
and the request/response headers look something like this:
Request:
POST /item/save HTTP/1.1
Host: services.mydomain.com
Accept: */*
Content-Length: 429
Expect: 100-continue
Content-Type: multipart/form-data
Response:
HTTP/1.1 100 Continue
HTTP/1.1 200 OK
Date: Fri, 06 Jul 2012 08:37:01 GMT
Server: Apache
Vary: Accept-Encoding,User-Agent
Content-Length: 256
Content-Type: application/json; charset=utf-8
followed by the body (json encoded data).
The problem is that the common thing is to split headers and body in the response by the first empty line encountered, except in this case, the empty line is after the 100 Continue and therefore everything else gets pushed into the body–and that is not valid json anymore :-)
So my question is this: What's the common way to deal with this?
I have 3 options lined up:
Specify that curl should not expect 100-continue? (How?)
Specify that curl should only send back the headers of the last response? (How?)
Manually check for 100 Continue headers and disregard them and their following empty line? (In that case, are there other similar things that could happen, that I should manually check for?)
Unless I'm missing something obvious, I'm sure people have stumbled upon this and solved it many times!
I will opt for #1.
You can force curl to send empty "Expect" header, by adding:
curl_setopt($ch, CURLOPT_HTTPHEADER,array("Expect:"));
to your code
If you want check it manually, you should define your own header callback and maybe write callback (look for CURLOPT_HEADERFUNCTION and CURLOPT_WRITEFUNCTION in curl_setopt doc), which has simply to ignore all "HTTP/1.1 100 Continue" headers.
Here's another method that uses the approach I described in the comment by parsing the response into header vs. body using CURLINFO_HEADER_SIZE:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://test/curl_test.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
// sets multipart/form-data content-type
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'field1' => 'foo',
'field2' => 'bar'
));
$data = curl_exec($ch);
// if you want the headers sent by CURL
$sentHeaders = curl_getinfo($ch, CURLINFO_HEADER_OUT);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
curl_close($ch);
$header = substr($data, 0, $headerSize);
$body = substr($data, $headerSize);
echo "==Sent Headers==\n$sentHeaders\n==End Sent Headers==\n";
echo "==Response Headers==\n$headers\n==End Response Headers==\n";
echo "==Response Body==\n$body\n==End Body==";
I've tested this, and it results in the following output:
==Sent Headers==
POST /curl_test.php HTTP/1.1
Host: test
Accept: */*
Content-Length: 242
Expect: 100-continue
Content-Type: multipart/form-data; boundary=----------------------------
d86ac263ce1b
==End Sent Headers==
==Response Headers==
HTTP/1.1 100 Continue
HTTP/1.1 200 OK
Date: Fri, 06 Jul 2012 14:21:53 GMT
Server: Apache/2.4.2 (Win32) PHP/5.4.4
X-Powered-By: PHP/5.4.4
Content-Length: 112
Content-Type: text/plain
==End Response Headers==
==Response Body==
**FORM DATA**
array(2) {
["field1"]=>
string(3) "foo"
["field2"]=>
string(3) "bar"
}
**END FORM DATA**
==End Body==
i had the same problem but this solution does note work for me, finaly i have found this methode and all its fine:
we have to prepare data post fields before sending them:
function curl_custom_postfields($curl, array $assoc = array(), array $files = array()) {
/**
* For safe multipart POST request for PHP5.3 ~ PHP 5.4.
* #param resource $ch cURL resource
* #param array $assoc "name => value"
* #param array $files "name => path"
* #return bool
*/
// invalid characters for "name" and "filename"
static $disallow = array("\0", "\"", "\r", "\n");
// build normal parameters
foreach ($assoc as $key => $value) {
$key = str_replace($disallow, "_", $key);
$body[] = implode("\r\n", array(
"Content-Disposition: form-data; name=\"{$key}\"",
"",
filter_var($value),
));
}
// build file parameters
foreach ($files as $key => $value) {
switch (true) {
case false === $value = realpath(filter_var($value)):
case !is_file($value):
case !is_readable($value):
continue; // or return false, throw new InvalidArgumentException
}
$data = file_get_contents($value);
$value = call_user_func("end", explode(DIRECTORY_SEPARATOR, $value));
$key = str_replace($disallow, "_", $key);
$value = str_replace($disallow, "_", $value);
$body[] = implode("\r\n", array(
"Content-Disposition: form-data; name=\"{$key}\"; filename=\"{$value}\"",
"Content-Type: application/octet-stream",
"",
$data,
));
}
// generate safe boundary
do {
$boundary = "---------------------" . md5(mt_rand() . microtime());
} while (preg_grep("/{$boundary}/", $body));
// add boundary for each parameters
array_walk($body, function (&$part) use ($boundary) {
$part = "--{$boundary}\r\n{$part}";
});
// add final boundary
$body[] = "--{$boundary}--";
$body[] = "";
// set options
return #curl_setopt_array($curl, array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => implode("\r\n", $body),
CURLOPT_HTTPHEADER => array(
"Expect: 100-continue",
"Content-Type: multipart/form-data; boundary={$boundary}", // change Content-Type
),
));}
you have to prepare two arrays:
1- post field with normal data: (name1 = val1, name2 = val2, ...)
2- post field with file data: (name_file 1, path_file1, name_file2 = path_file2, ..)
and finaly call this function before executing curl like this.
$r = curl_custom_postfields($curl, $post, $postfields_files);
I have come across this with 100s and 302s etc it's annoying but sometimes needed (gdata calls etc) so i would say leave curl returning all headers and extract the body a little differently.
I handle it like this (can't find my actual code but you'll get the idea):
$response = curl_exec($ch);
$headers = array();
$body = array();
foreach(explode("\n\n", $response) as $frag){
if(preg_match('/^HTTP\/[0-9\.]+ [0-9]+/', $frag)){
$headers[] = $frag;
}else{
$body[] = $frag;
}
}
echo implode("\n\n", $headers);
echo implode("\n\n", $body);
I begrudge the longwinded hackish method (would prefer it if curl marked the body content somehow) but it has worked well over the years. let us know how you get on.