This headers sends by my programs to a adress:
--55ae49448a20c
Content-Disposition: form-data; name="chat_id"
Content-Length: 9
108432389
--55ae49448a20c
Content-Disposition: form-data; name="photo"; filename="Untitled.png"
Content-Length: 16252
Content-Type: image/png
PNG
I want to POST 2 varibles (chat_id) and (photo) by the following code.
Attempted Code:
<?php
$params = "Content-Disposition: form-data; name=\"chat_id\"\r\n"
. "Content-Length: 9\r\n\r\n"
. "\r\n"
. "Content-Disposition: form-data; name=\"photo\"; filename=\"Untitled.png\"\r\n"
. "Content-Length: ".filesize("Untitled.png")."\r\n"
. "Content-Type: image/png\r\n\r\n"
. file_get_contents("Untitled.png");
$request_headers = array();
$request_headers[] = 'Content-Length: ' . strlen($params);
$url = 'http://example.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
$reply = curl_exec($ch);
?>
Is there any other way for do that !?
My attempted code gives me 400 Bad Gatway error..
That's TOTALLY unnecessary. You're doing way too much that CURL can do far better (and properly) itself.
$post = array(
'chat_id' => 108432389,
'photo' => '#Untitled.jpg'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
old-school php curl used # in the value field to signify a file to be uploaded. Newer versions use curlfile instead.
Related
UPDATE: Below code works for me. Hope it helps someone to figure out their problem.
After having several errors, it helped going back and looking at all possible error codes on Apple News Developer site.
Look at specific error numbers in your code and decide what might be wrong with it.
Follow the examples on the Apple News Developer site. Even though they are vague they do contain crucial information!
//set the timezone
date_default_timezone_set('UTC');
//get json to be sent
$raw = file_get_contents('article.json');
$eol = "\r\n";
$data = '';
$bound= '535e329ca936f79a19ac9a251f7d48f7';
$data='--'.$bound.$eol.
"Content-Type: application/json" . $eol.
"Content-Disposition: form-data; name=metadata" . $eol. $eol.
'{
"data": {
"isCandidateToBeFeatured": "false",
"isSponsored": false,
"isPreview": true
}
}' .$eol.
'--'.$bound.$eol.
"Content-Type: application/json" . $eol.
"Content-Disposition: form-data; filename=article.json; name=article.json".$eol.$eol.
$raw.$eol.
'--'.$bound.'--'.$eol.$eol;
//set variables
$http_method = 'POST';
$date = gmdate('Y-m-d\TH:i:s\Z');
$key = 'xxx';
$url = 'https://news-api.apple.com/channels/xxx/articles';
$secret = 'xxx';
//cannonical request
$canonical_request = $http_method . $url . $date. 'multipart/form-data; boundary=535e329ca936f79a19ac9a251f7d48f7' . $data;
//Signature
$secretKey = base64_decode($secret);
$hash = hash_hmac('sha256', $canonical_request, $secretKey, true);
$signature = base64_encode($hash);
$authHeader = "HHMAC; key=$key; signature=$signature; date=$date;";
$headers = array();
$headers[] = "Authorization: $authHeader";
$headers[] = "Accept: application/json";
$headers[] = "Content-Type: multipart/form-data; boundary=535e329ca936f79a19ac9a251f7d48f7";
$headers[] = "Content-Length: ".strlen($data);
//curl options
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//get result
$server_output = curl_exec ($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo $status;
curl_close ($ch);
print_r(json_decode($server_output));
Your content type header should be Content-Type: application/json but the content type for authorization is just the value `application/json'.
Try to use that in the canonical request instead of the full header.
Your Content-type header is missing, add it like this:
$headers[] = $Content_Type;
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 be able to code in php the equivalent to this curl command:
curl -F out=json --form-string 'content=<!DOCTYPE html><html><head><title>check it</title></head><body></body></html>' http://validator.w3.org/nu/
This curl command returns json as expected.
Maybe I am missing something from their documentation here:
https://github.com/validator/validator/wiki/Service:-Input:-POST-body and https://github.com/validator/validator/wiki/Service%3A-HTTP-interface
The problem that I have now is that the web service returns html instead of json.
Although I am setting the header accept to json it does not work. I also tried to set both accept and Content-Type but this triggers an error from the web service saying non valid input. Here is the code that I need your help with:
$html = "<!DOCTYPE html><html><head><title>test</title></head><body></body></html>";
$endPoint = "http://validator.w3.org/nu/";
$timeout = 5000;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endPoint);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, $timeout);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch,CURLOPT_POSTFIELDS, array('content' => $html, 'out' => 'json'));
$output = curl_exec($ch);
if(curl_errno($ch))
{
echo curl_error($ch);
}
curl_close($ch);
error_log(__FILE__. ": " . __LINE__ . ": " . var_export($output, true));
echo $output;
After reading Ignacio question I am updating with this information from w3c documentation page:
In their documentation they say the html string should be sent in http body and in their java library they are using this:
String response = null;
String source = "your html here";
HttpResponse<String> uniResponse = Unirest.post("http://localhost:8080/vnu")
.header("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36")
.header("Content-Type", "text/html; charset=UTF-8")
.queryString("out", "gnu")
.body(source)
.asString();
response = uniResponse.getBody();
Could this be a hint for you? Just to let you know I tried both
http://validator.w3.org/nu/?out=json
and
http://validator.w3.org/nu/
endpoints (as value of $endPoint variable in php script above).
To get the result that you are looking for, you have to send your data as multipart/form-data (you can take a look on the validator page or the request sent by curl to see that data is sent as multipart/form-data ), for that take this example :
$url = 'http://validator.w3.org/nu/';
$html = '<!DOCTYPE html><html><head><title>test</title></head><body></body></html>';
$boundary = 'your-boundary';
$body = '--' . $boundary . "\r\n";
// set the "out" as "json"
$body .= 'Content-Disposition: form-data; name="out"' . "\r\n" . "\r\n";
$body .= 'json' . "\r\n";
$body .= "--" . $boundary ."\r\n";
// set the "content"
$body .= 'Content-Disposition: form-data; name="content"' . "\r\n" . "\r\n";
$body .= $html . "\r\n";
$body .= "--" . $boundary . "--" . "\r\n" . "\r\n";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data; boundary='.$boundary));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
echo curl_exec($ch);
curl_close($ch);
Then you'll get something like this :
{
"messages": [{
"type": "info",
"message": "The Content-Type was “text/html”. Using the HTML parser."
}, {
"type": "info",
"message": "Using the schema for HTML with SVG 1.1, MathML 3.0, RDFa 1.1, and ITS 2.0 support."
}],
"source": {
"type": "text/html",
"encoding": "utf-8",
"code": "<!DOCTYPE html><html><head><title>test</title></head><body></body></html>"
}
}
Hope that can help.
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);