I am trying to upload document via curl-put method. But when I call this file its just generate 0 byte file not uploading file.
I am consuming third party's web service.
What is missing here ?Is there something in header ?
In file-name do we need to pass file-name or path ?
PHP Code
$data = json_encode($this->data);
$file_url = $filepath;
$f = array($filepath);
$eol = "\r\n";
$BOUNDARY = md5(time());
$BODY=""; //init my curl body
$BODY.= '--'.$BOUNDARY. $eol; //start param header
$BODY .= 'Content-Disposition: form-data; name="Appointment"' . $eol . $eol; // last Content with 2 $eol, in this case is only 1 content.
$BODY.= '--'.$BOUNDARY. $eol; // start 2nd param,
$BODY.= 'Content-Disposition: form-data; filename='.$filepath. $eol ; //first Content data for post file, remember you only put 1 when you are going to add more Contents, and 2 on the last, to close the Content Instance
$BODY.= 'Content-Type: application/pdf' . $eol; //Same before row
$BODY.= chunk_split(base64_encode(file_get_contents($file_url))) . $eol; // we write the Base64 File Content and the $eol to finish the data,
$BODY.= '--'.$BOUNDARY .'--' . $eol. $eol; // we close the param and the post width "--" and 2 $eol at the end of our boundary header.
$header[] = 'Authorization: WRAP access_token="'.$this->accesstoken.'"';
$header[] = 'Content-Type: multipart/form-data; boundary='.$BOUNDARY;
print_r($BODY);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$this->baseAddress);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); // tell curl you want to post something
curl_setopt($ch, CURLOPT_POSTFIELDS, $BODY); // define what you want to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1);
$output = curl_exec ($ch); // execute
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($output, 0, $header_size);
$this->response = substr($output, $header_size);
$info = curl_getinfo($ch);
$this->responsecode = $info['http_code'];
curl_close ($ch); // close curl
I also tried to send file by creating object. In this case it gives below error.
$cfile = new CURLFile(realpath('testcp.txt'),'text/plain');
$uploadPost = array (
'file' => $cfile
);
$eol = "\r\n";
$BOUNDARY = md5(time());
$BODY=""; //init my curl body
$BODY.= '--'.$BOUNDARY. $eol; //start param header
$BODY.= '--'.$BOUNDARY. $eol; // start 2nd param,
$BODY.= '--'.$BOUNDARY .'--' . $eol. $eol; // we close the param and the post width "--" and 2 $eol at the end of our boundary header.
$header[] = 'Authorization: WRAP access_token="'.$this->accesstoken.'"';
$header[] = 'Content-Type: multipart/form-data; boundary='.$BOUNDARY;
print_r($BODY);
//ECHO $this->accesstoken;EXIT;
$ch = curl_init();
//echo $this->baseAddress;exit;
curl_setopt($ch, CURLOPT_URL,$this->baseAddress);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); // tell curl you want to post something
// curl_setopt($ch, CURLOPT_POSTFIELDS, ($data)); // define what you want to post
curl_setopt($ch, CURLOPT_POSTFIELDS, $uploadPost); // define what you want to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1);
$output = curl_exec ($ch); // execute
echo 'OUTPUT ---';print_r($output);exit;
curl_close ($ch);
Error :
Unexpected end of MIME multipart stream. MIME multipart message is not
complete.
Try this:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array("body" => $BODY)));
Or at least URL-encode $BODY;
Related
I have tried to call API for send image file using CURL .But I am getting below error:
"statusCode":415,
"error":"Unsupported Media Type"
Please help me.
I have attached code here:
$filename = "screenshot.jpg";
$handle = fopen($filename, "r");
$xml = fread($handle, filesize($filename));
fclose($handle);
$jwt_token = "xxx";
$authorization = "Authorization:".$jwt_token;
$url = "https://prod0-commerce-api.sprinklr.com/media_upload";
$headers = array(
"Content-Type: image/jpg]",
"Cache-Control: no-cache",
"Pragma: no-cache",
$authorization
);
$postdata = array('fileName' => '#'.$filename,
'type' => 'IMAGE'); //<-------------
$soap_do = curl_init();
curl_setopt($soap_do, CURLOPT_URL, $url);
//curl_setopt($soap_do, CURLOPT_CONNECTTIMEOUT, 60);
//curl_setopt($soap_do, CURLOPT_TIMEOUT, 60);
curl_setopt($soap_do, CURLOPT_RETURNTRANSFER, true );
curl_setopt($soap_do, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($soap_do, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($soap_do, CURLOPT_POST, true );
curl_setopt($soap_do, CURLOPT_POSTFIELDS, $postdata); //<-----------
curl_setopt($soap_do, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($soap_do);
// Check for errors and display the error message
curl_close($soap_do);
$httpcode = curl_getinfo($soap_do, CURLINFO_HTTP_CODE);
echo $httpcode;
echo "<pre>";
var_dump($result);
if($errno = curl_errno($soap_do)) {
$error_message = curl_strerror($errno);
echo "cURL error ({$errno}):\n {$error_message}";
}
echo "string";exit();
print_r($result);
The problem is in this block:
$postdata = array('fileName' => '#'.$filename,
'type' => 'IMAGE'); //<-------------
The value of type should be a valid MIME type (aka "media type" or "content type").
A MIME type is an identifier composed of two parts (the type and the subtype) joined by slash (/).
The type identifies the category of content (text, image, audio, video, application etc). The subtype identifies more accurate the content inside the category.
For images, the type is image and there are several subtypes: gif, jpeg, png etc.
A correct MIME type for an image file looks like image/jpeg or image/png and not just IMAGE. This is why the server rejects your query.
The PHP function getimagesize() can be used to find the MIME type of a image stored in a file.
Your code should be like this:
$imgInfo = getimagesize($filename);
$postdata = array('fileName' => '#'.$filename,
'type' => $imgInfo['mime']);
And no, there is no setting in php.ini that writes correct code for you.
I have solved using this solution
<?php
$file = "http://localhost/xxx/screenshot.jpg";
$boundary = md5(time());
$eol = "\r\n";
$params = "----".$boundary.$eol
. "Content-Disposition: form-data;name=\"type\"".$eol
. $eol
. "IMAGE"
. $eol
. "----".$boundary.$eol
. "Content-Disposition: form-data;name=\"file\"; filename=\"screenshot.jpg\"".$eol
. '"Content-Type: image/jpeg\"'.$eol
. $eol
. file_get_contents($file) .$eol
. "----".$boundary."--";
$jwt_token = "xxxx";
$authorization = "Authorization:".$jwt_token;
$first_newline = strpos($params, $eol);
$multipart_boundary = substr($params, 2, $first_newline - 2);
$request_headers = array();
$request_headers[] = $authorization;
$request_headers[] = 'Accept: application/json';
$request_headers[] = 'Content-Length: ' . strlen($params);
$request_headers[] = 'Content-Type: multipart/form-data; boundary='. $multipart_boundary;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'xxx');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
echo "<pre>";
print_r($result);
exit();
Most of time a error 415 appears when you don't set properly the Content-Type. Maybe you can put Content-Type:
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: image/jpg"));
I need your help with multipart/form-data and uploading image with curl.
I have this code for generating and sending data:
$boundary = '----WebKitFormBoundaryLZI2dppfUIcXxqT0';
$eol = "\r\n";
$postdata = '';
$postdata .= '--'.$boundary.$eol;
$postdata .= 'Content-Disposition: form-data; name="scrid"'.$eol.$eol;
$postdata .= $scrid.$eol;
$postdata .= '--'.$boundary.$eol;
$postdata .= 'Content-Disposition: form-data; name="file"; filename="'.$filepath.'"'.$eol;
$postdata .= "Content-Type: {$imginfo['mime']}".$eol.$eol;
$postdata .= $img.$eol;
$postdata .= '--'.$boundary.'--';
$headers = array(
"Content-Length: " . strlen($postdata),
"Content-Type: multipart/form-data;boundary=----WebKitFormBoundaryLZI2dppfUIcXxqT0",
"X-Requested-With: XMLHttpRequest",
"Origin:http://www.ebayclassifieds.com",
"Accept-Encoding: gzip, deflate",
"Accept:application/json, text/javascript, */*;",
);
curl_setopt($this->_ch, CURLOPT_URL, 'http://www.ebayclassifieds.com/m/ImageUpload');
curl_setopt($this->_ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($this->_ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($this->_ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($this->_ch, CURLOPT_POST, 1);
curl_setopt($this->_ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($this->_ch, CURLOPT_COOKIEJAR, $this->_cookieFilePath);
curl_setopt($this->_ch, CURLOPT_COOKIEFILE, $this->_cookieFilePath);
curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->_ch, CURLOPT_REFERER, "http://www.ebayclassifieds.com/m/PostAd?scrid=$scrid");
$imageForm = curl_exec($this->_ch);
and i have request payload:
------WebKitFormBoundaryibLm7G5cqxCOuAFy
Content-Disposition: form-data; name="file"; filename="1-g-0-032- oz-silver-valcambi-bullion-bar-999-rev.jpg"
Content-Type: image/jpeg
Here appears the souce of the image itself like "ÿØÿàÿØÿàÿØÿàÿØÿàÿØÿàÿØÿà"
------WebKitFormBoundaryibLm7G5cqxCOuAFy
Content-Disposition: form-data; name="scrid"
32482346-7100587438898460646
------WebKitFormBoundaryibLm7G5cqxCOuAFy--
How can i get source of image?
I trying to get source: $imgSource = file_get_contents($filepath), but after send this text, server return error 417.
If send not valid parament for image, server return json request with error messages(this in normally)
Resolved.
Need send Expect: 0 in headers.
I want to fetch some data from 12.96.12.174 this IP address using http post by XML. I create curl PHP code for that
<?php
$url = "http://12.96.12.174";
$post_string = '<?xml version="1.0"?>
<CRMAcresMessage>
<Header ImmediateResponseRequired="true" OriginalBodyRequested="true">
<MessageID>25</MessageID>
<TimeStamp>2016-03-11T011:35:11</TimeStamp>
<Operation Operand="Request" Data="PlayerProfile" />
</Header>
<PlayerID>59979</PlayerID>
<Body>
</Body>
</CRMAcresMessage>';
$header = "POST HTTP/1.0 \r\n";
$header .= "Content-type: text/xml \r\n";
$header .= "Content-length: ".strlen($post_string)." \r\n";
$header .= "Content-transfer-encoding: text \r\n";
$header .= "Connection: close \r\n\r\n";
$header .= $post_string;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL,$url);
//$fp = fopen('rss.xml', 'w');
curl_setopt($ch,CURLOPT_PORT, 8085);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $header);
echo $data = curl_exec($ch);
if(curl_errno($ch))
print curl_error($ch);
else
curl_close($ch);
?>
When I hit that link from "http://example.com/members/check.php" this url this gives me Recv failure: Connection was reset in Curl.
And from my localhost I got Failed to connect
php version is also >5.3
I am beginner in Curl.
curl_setopt($ch, CURLOPT_URL, trim($url));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
For Recv failure: Connection was reset in Curl PHP ==>
Declare like this :
CURLOPT_SSL_VERIFYPEER as 0
& make sure that you are using PHP version >5.3
I've reviewed the old questions posted here on Stackoverflow about this issue.
But I didn't find any example for php integration.
Here is a sample of my code to do that but it's failing
$url = 'https://connect.squareup.com/v1/me/items/9999999/image';
$auth_bearer = 'Authorization: Bearer ' . $this->accessToken;
$image_data = base64_encode(file_get_contents('image.jpeg'));
$header = array(
$auth_bearer,
'Accept: application/json',
'Content-Type: multipart/form-data; boundary=BOUNDARY',
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'files=' . $image_data);
$head = curl_exec($ch);
curl_close($ch);
$response = json_decode($head);
echo "<pre>";
print_r($response);
echo "</pre>";
And nothing happens... any help here?
Thanks
You need to post the raw image data (not base64 encoded) with the proper multipart header for a file object. Here's a working example (replace ACCESS_TOKEN, ITEM_ID, and IMAGE_FILE).
<?php
function uploadItemImage($url, $access_token, $image_file) {
$headers = ["Authorization: Bearer $access_token"];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ['image_data' => "#$image_file"]);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$return_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
print "POST to $url with status $return_status\n";
curl_close($ch);
return $data ? json_decode($data) : false;
}
print_r(
uploadItemImage(
'https://connect.squareup.com/v1/me/items/ITEM_ID/image',
'ACCESS_TOKEN',
'IMAGE_FILE.jpg'
)
);
?>
Here is my PHP implementation for uploading a PNG image. Sometimes a different code view helps.
As #Troy stated, the important field to include for images is 'Content-Type: multipart/form-data'. Everything else I upload to Square uses 'Content-Type: application/json'.
$square_url = 'https://connect.squareup.com/v1/me/items/' . $square_item_id . '/image';
$cfile = new CURLFile($image_path_on_server, 'image/png', 'image_data');
$image_data = array('image_data' => $cfile);
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer ' . $access_token,
'Content-Type: multipart/form-data',
'Accept: application/json'
));
curl_setopt($curl, CURLOPT_POSTFIELDS, $image_data);
curl_setopt($curl, CURLOPT_URL, $square_url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, TRUE);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($curl, CURLOPT_VERBOSE, TRUE);
$json = curl_exec($curl);
curl_close($curl);
Strictly speaking Square API documentation, their method can be implemented keeping a few things in mind.
-- Your request must be enclosed in a boundary and contain the Content disposition, name, filename, content type like the sample below.
--BOUNDARY
Content-Disposition: form-data; name="image_data"; filename="MyImage.png"
Content-Type: image/png
{BLANK LINE IS REQUIRED}
IMAGE BINARY DATA GOES HERE
--BOUNDARY--
In essence, the format of the request must be exactly as specified in the sample. This includes the 'boundary', the newline characters, the necessary headers, a blank line between the headers (for some reason nothing works if the line isn't present), and the actual image binary data. NOTE: the boundary can be any string that you choose, but it must be used consistently. In code, this would look something like this:
$boundary = "---------------------" . md5(mt_rand() . microtime());
$imageToUpload = "--{$boundary}" . "\r\n" .
"Content-Disposition: form-data; name=\"image_data\"; filename=\"" . $full_path_to_image_file . "\"" . "\r\n" .
"Content-Type: image/jpeg" . "\r\n" .
"\r\n" . // <- empty line is required
(file_get_contents($full_path_to_image_file)) . "\r\n" .
"--{$boundary}--";
The above will produce a request that looks like this:
-----------------------51b62743876b1201aee47ff4b1910e49
Content-Disposition: form-data; name="image_data"; filename="/some/directory/image.jpg"
Content-Type: image/jpeg
����
-----------------------51b62743876b1201aee47ff4b1910e49--
-- Technically speaking, the Content-Type in the request must change with the type of image you're uploading (image/jpeg or image/png). You can set the content type to application/octet-stream to cover all basis.
-----------------------51b62743876b1201aee47ff4b1910e49
Content-Disposition: form-data; name="image_data"; filename="/some/directory/image.jpg"
Content-Type: application/octet-stream
����
-----------------------51b62743876b1201aee47ff4b1910e49--
The two examples above will upload an image.
-- 'Image binary data' can be misleading as my every search showed that an image binary is obtained by using the base64_encode function. In my experiments, the base64_encoding doesn't do anything. You only need to open the file with the file_get_contents.
-- In your cURL request, must have the header's Content-Type set to multipart/form-data and have the same boundary as the request. Example below:
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $personalAccessToken, 'Content-Type: multipart/form-data; boundary=' . $boundary ));
So this adds another solution to the mix.
Troy's solution using # is deprecated and I was unable to get it to work. Byron's solution works with the CURLOPT_POST before the CURLOPT_POSTFIELDS (see Mavooks comment at https://www.php.net/manual/en/function.curl-setopt.php) and removing the Content-Type from the header. That is because it is automatically multipart if CURLOPTS_POSTFIELDS is an array and manually including it seems to override it, but then it is missing the boundary.
$square_url = 'https://connect.squareup.com/v1/me/items/' . $square_item_id . '/image';
$cfile = new CURLFile($image_path_on_server, 'image/png', 'image_data');
$image_data = array('image_data' => $cfile);
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer ' . $access_token,
'Accept: application/json'
));
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $image_data);
curl_setopt($curl, CURLOPT_URL, $square_url);
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, TRUE);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($curl, CURLOPT_VERBOSE, TRUE);
$json = curl_exec($curl);
curl_close($curl);
I am trying to send XML data through CURL with HTTP POST in PHP script. I am getting following message on execution.
Found
The document has moved here.
And here is my code.
<?php
$url = "https://usm.channelonline.com/REQUEST";
$post_string = '<export_documents_request schemaVersion="4.0">
<options>
<onlyUnexported>false</onlyUnexported>
<eventInRange>
<eventType>modified</eventType>
<after>2005-01-01T10:00:00Z</after>
</eventInRange>
</options>
</export_documents_request>';
$header = "POST HTTP/1.1 \r\n";
$header .= "Content-type: text/xml \r\n";
$header .= "Content-length: ".strlen($post_string)." \r\n";
$header .= "Content-transfer-encoding: text \r\n";
$header .= "Connection: close \r\n\r\n";
$header .= $post_string;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,TRUE);
curl_setopt($ch,CURLOPT_MAXREDIRS,10);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $header);
$data = curl_exec($ch);
if(curl_errno($ch))
print curl_error($ch);
else
echo $data;
curl_close($ch);
?>
And here is screen view on execution.
I am good in PHP but just familiar with CURL. Can you help me out how to fix this issue?
Either, like MrCode pointed out, the server doesn't really respond with 301/302 or your PHP is running in safe mode, which doesn't allow for using CURLOPT_FOLLOWLOCATION.