curl post multipart/form-data api - php

I can not send pictures.
More information - Telegram
https://core.telegram.org/bots/api#sendphoto
I want to send a picture, this method is useless.
Are there any other method?
<?php
$Photo = "http://www.pawprint.net/images/news/1-4fac83467069c.png";
$IDUser = 26034352;
$Data = array(
'chat_id' => $IDUser,
'photo' => $Photo,
'caption' => 'hi'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.telegram.org/bot93816942:AAHnjqsjpJjRItc7ySbUq4C5IRLqytpPK6k/sendPhoto");
curl_setopt($ch, CURLOPT_POST, 1);
//curl_setopt($ch, CURLOPT_POSTFIELDS,$options);
// in real life you should use something like:
curl_setopt($ch, CURLOPT_POSTFIELDS,
http_build_query($Data));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// frther processing ....
if ($server_output == "OK") {
echo "ok";
}
?>

I see you want to send a picture located on a external server with its URL
so you can do as follow
define('website', 'https://api.telegram.org/bot<bot-token>');
function send($method, $datas)
{
$url = website . "/" . $method;
if (!$curld = curl_init()) {
exit;
}
curl_setopt($curld, CURLOPT_POST, true);
curl_setopt($curld, CURLOPT_POSTFIELDS, $datas);
curl_setopt($curld, CURLOPT_URL, $url);
curl_setopt($curld, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($curld);
curl_close($curld);
}
now just call this function with proper method name and data. example for sending a photo:
$postfields = array(
'chat_id' => $ChatID,
'photo' => "http://url.of/photo.jpg"
);
send("sendPhoto", $postfields);

Related

I don't get a JSON response while using PHP curl

I am trying to call the GitHubAPI but when I do curl_exec() the response is a simple string. I would like to get a JSON response. My code is as follows:
if(isset($_GET['code']))
{
global $CLIENTID, $CLIENTSECRET;
$CODE = $_GET['code'];
$postfields = array('client_id' => $CLIENTID, 'client_secret' => $CLIENTSECRET, 'code' => $CODE);
$json_fields = json_encode($postfields);
$ch = curl_init("https://github.com/login/oauth/access_token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type"=>"x-www-form-urlencoded", "Accept"=>"application/json"));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
$gitResponse = curl_exec($ch);
curl_close ($ch);
if($gitResponse)
{
echo var_dump($gitResponse);
}
else
{
echo "Error";
}
}
else
{
echo '<a href="https://github.com/login/oauth/authorize?client_id='.$CLIENTID.'" title="Login with Github">
LOGIN
</a>';
}
I've tried with CURLOPT_HTTPHEADER but it didn't work so I commented it.
What I receive is good but it is a string instead of a JSON respone so I can't use the fields of the response.
Thank you!
Add this to your code:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
This will request the server to return a JSON string, then you can turn that to an array to use:
if($gitResponse)
{
$result = json_decode($gitResponse,true);
}

Upload file using Curl and receive them in Laravel method

I have been trying to upload file to using curl using laravel app end point.
Below code is on separate server.
$header = $this->getCurlHeader();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$this->url);
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
// curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$cfile = new \CURLFile($this->filePath . $this->csvFile, 'text/csv','text.csv');
//print_r($cfile);exit;
$postData = array('csv' => $cfile);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$response = curl_exec($ch);
$hhtpCode = curl_getinfo($ch);
curl_close($ch);
//$this->dbg($hhtpCode);
$this->dbg(json_decode($response,1),1);
And receiving end in laravel app hosted on different server.
public function insert(Request $request, $feed=''){
//return response()->json(var_dump($request->all()));
//return response()->json("here in insert");
return response()->json($_FILES);
echo "here";
dd($_FILES);
}
It returns me empty response.
I am able to verify curl request using headers.
Any suggestion will be helpful.
Thanks.
You can try something like this on the source server instead:
$target_url = 'https://mywebsite.com'; // Write your URL here
$dir = '/var/www/html/storage/test.zip'; // full directory of the file
$cFile = curl_file_create($dir);
$post = array('file'=> $cFile); // Parameter to be sent
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=json_decode(curl_exec($ch));
curl_close ($ch);
From the destination server, print the request sent.
public function insert(Request $request){
dd($request->file);
}
please use curlfile method to upload files.
if(isset($_FILES) && !empty($_FILES['identity_doc']))
{
foreach($_FILES['identity_doc'] as $key => $file)
{
$data['document'.$i]= new CURLFile($_FILES['identity_doc']['tmp_name'][$i], $_FILES['identity_doc']['type'][$i],$_FILES['identity_doc']['name'][$i]);
}
}
if(isset($_POST['submit']))
{
$fileName=$_FILES['resume']['name'];
$type=$_FILES['resume']['type'];
$tempPathname=$_FILES['resume']['tmp_name'];
$handle = fopen($tempPathname, "r");
$POST_DATA = fread($handle, filesize($tempPathname));
$url="https://objectstorage.region-name.oraclecloud.com/p/par-id/n/namespace`enter code here`/b/bucket-name/o/images/".$fileName;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS=>$POST_DATA ,
CURLOPT_HTTPHEADER => array(
'Content-Type: '.$type,
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($response) {
echo 'error';
} else {
echo $url;
}
}
?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="resume">
<button type="submit" name="submit">submit</button>
</form>

how to view final url before submission curl php

I want to know final url just before executing curl to check all parameters passing as desired. how to view that.
<?PHP
function openurl($url) {
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
curl_close($ch);
echo $content;
}
$postvars = array('user' => "user123",'password' => "user#user!123",'Text' => "Test");
$sms_url ="http://remoteserver/plain";
openurl($sms_url);
?>
desired output to check all params and its values passing correct..
http://remoteserver/plain?user=user123&password=user#user!123&Text=TESThere
You forgot to add the $postvars as parameter to your function.
function openurl($url, $postvars) {
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
curl_close($ch);
echo $content;
}
$postvars = array('user' => "user123",'password' => "user#user!123",'Text' => "Test");
$sms_url ="http://remoteserver/plain";
// create a test var which we can display on screen / log
$test_url = sms_url . http_build_query($postvars);
// either send it to the browser
echo $test_url;
// or send it to your log (make sure loggin is enabled!)
error_log("CURL URL: $test_url", 0);
openurl($sms_url, $postvars);

paypal MALFORMED REQUEST error in curl

I am facing MALFORMED_REQUEST in paypal API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.sandbox.paypal.com/v1/payments/payment");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{
\"intent\":\"authorize\",
\"payer\":{
\"payment_method\":\"credit_card\",
\"funding_instruments\":[{
\"credit_card\":{
\"number\":\"5555555555554444\",
\"type\":\"mastercard\",
\"expire_month\":07,
\"expire_year\":22,
\"cvv2\":123,
\"first_name\":\"FName\",
\"last_name\":\"Lname\",
\"billing_address\":{
\"line1\":\"address,\",
\"city\":\"City\",
\"state\":\"state\",
\"postal_code\":\"postal_code\",
\"country_code\":\"country_code\"
}
}
}]
},
\"transactions\":[{
\"amount\":{
\"total\":\"10\",
\"currency\":\"CAD\",
\"details\":{
\"subtotal\":\"10\",
\"tax\":\"0\",
\"shipping\":\"0\"
}
}
}]}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: application/json";
$headers[] = "Authorization: Bearer myAccessToken";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
Here I am calling curl for authorization with paypal
jsonlint.com shows this json format is ok
But still I am getting response like,
{"name":"MALFORMED_REQUEST","message":"The request JSON is not well formed.","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST","debug_id":"9d7454a8637ae"}
Not getting exactly where I am wrong? Does any one know? Thanks in advance!
Your problem is the 07 in "expire_month": 07. I assume this value is meant to be a string. Not sure what you pasted in to jsonlint but it wasn't the JSON in your question.
As indicated in the comments, don't roll your own JSON. Use the tools available
$data = [
'intent' => 'authorize',
'payer' => [
'payment_method' => 'credit_card',
'funding_instruments' => [[
'credit_card' => [
'number' => '5555555555554444',
'type' => 'mastercard',
'expire_month' => '07',
'expire_year' => '22',
'hopefully you get the idea' => 'by now'
]
]]
]
];
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
As the error indicates, your JSON is not formed correctly.You need not pass \ to escape your request parameters . Try removing those or try this sample code which works out of the box.
<?php
$data = 'response_type=token&grant_type=client_credentials';
$headers_arr = array();
$headers_arr[]="Accept-Encoding:application/json;charset=utf-8";
$headers_arr[]="Accept-Language:en_US";
// $headers_arr[]="Authorization:Bearer AZHFuBBAIG1rP98P7Svn2WOVatM5KAllu6KvrTE8GGT4gt9vdfj8TtR_1Cer:EBTMERCurtbf_4auykCeGWYGvwsy147bSb3xCuYpohmouVBGTaYFUIRwWgbx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/oauth2/token");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);// this is used to bypass the SSL protocol, not recommended.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);// this is used to bypass the SSL protocol, not recommended.
curl_setopt($ch, CURLOPT_TIMEOUT, 45);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "ARLg-BBMeTGLU5IHCsdIKEC_R_sMAkWM-yLsI5W5u9RuhvNhgolhYv-1cWmr:EJdAYxDx29McgMKOWjGK1OLHyaIxQBRuV9sWgfFSeMKGVBe-1jdiNgv5TLtP");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_arr);
$result = curl_exec($ch);
$res = json_decode($result);
$access_token = $res->access_token;
//now create a paypal payment
$headers_arr = array();
$headers_arr[]="Content-Type:application/json;charset=utf-8";
$headers_arr[] = "Authorization: Bearer $access_token";
// echo '<pre>';
// print_r($headers_arr);
$data_string = '{
"intent":"authorize",
"payer":{
"payment_method":"credit_card",
"funding_instruments":[
{
"credit_card":{
"number":"4446283285273500",
"type":"visa",
"expire_month":11,
"expire_year":2018,
"cvv2":"874",
"first_name":"Betsy",
"last_name":"Buyer",
"billing_address":{
"line1":"111 First Street",
"city":"Saratoga",
"state":"CA",
"postal_code":"95070",
"country_code":"US"
}
}
}
]
},
"transactions":[
{
"amount":{
"total":"7.47",
"currency":"USD",
"details":{
"subtotal":"7.41",
"tax":"0.03",
"shipping":"0.03"
}
},
"description":"This is the payment transaction description."
}
]
}';
// echo data_string;
$chs = curl_init();
curl_setopt($chs, CURLOPT_URL, 'https://api.sandbox.paypal.com/v1/payments/payment');
curl_setopt($chs, CURLOPT_POST, true);
curl_setopt($chs, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($chs, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($chs, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($chs, CURLOPT_TIMEOUT, 45);
curl_setopt($chs, CURLOPT_RETURNTRANSFER, true);
curl_setopt($chs, CURLOPT_POST, 1);
curl_setopt($chs, CURLOPT_HTTPHEADER, $headers_arr);
if(curl_exec($chs) === false)
{
echo 'Curl error: ' . curl_error($chs);
}
$results = curl_exec($chs);
$res = json_decode($results);
echo 'ress=<pre>';
print_r($results);

Curl POST attachment

I need to attach a pdf file form local drive and post it to the API using PHP CURL.
Here is the RingCentral FaxOut API Documentation
$url = "https://service.ringcentral.com/faxapi.asp";
$data = array(
'Username' => 'XXXXXXXXX',
'Password' => 'XXXXXXXXX',
'Recipient' => 'XXXXXXXXXX|Navneet',
'Coverpage' => 'Default',
'Coverpagetext' => 'Testing Faxout API ',
'Resolution' => 'High',
"Sendtime" => date('d:m:y H:i:s'),
'Attachment' => file_get_contents(PATH_TO_FILE)
);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch,CURLOPT_POST, count($data));
curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
API do not return anything in response. I think, I'm not sending the attachment properly. The attachment should be in binary stream. I tried base64_encode but no success.
As given in the Request body example, header for attachment should be like this
Content-Disposition: form-data; name="Attachment"; filename="C:\example.doc"
<Document content is here>
-----------------------------7d54b1fee05aa
You can POST anything to the api with CURL, $doc in my example is anything you want to post , it can be a json_encoded file , a base64_encoded image or pdf or anything else.
$baseUri = https://service.ringcentral.com/faxapi.asp;
$doc = file_get_contents(PATH_TO_FILE);
$ci = curl_init();
curl_setopt($ci, CURLOPT_URL, $baseUri);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ci, CURLOPT_FORBID_REUSE, 0);
curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ci, CURLOPT_POSTFIELDS, $doc);
// also you can specify any specific header like this :
$h1['Content-Disposition'] = 'Content-Disposition'. ': ' . 'form-data'; // headers are key-value pairs right ?
curl_setopt($ci, CURLOPT_HTTPHEADER, array_values($h1)); // you can use this line for each header as a new key-value pair
$h2['name'] = 'name'. ': ' . 'Attachment';
curl_setopt($ci, CURLOPT_HTTPHEADER, array_values($h2));
$h3['filename'] = 'filename'. ': ' . 'C:\example.doc';
curl_setopt($ci, CURLOPT_HTTPHEADER, array_values($h3));
$response = curl_exec($ci);
**NOTE ** : its a good Idea to first of all check to see if your file_get_contents function works :
so in another php file check to see this :
echo file_get_contents(PATH_TO_FILE);
See if it echoes correctly
This is the function and how I generated the info for the request
function send_curl_request_with_attachment($method, $headers, $url, $post_fields) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
if($headers != "" && count($headers) > 0){
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
} curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_VERBOSE,true);
$result = curl_exec($ch);
curl_close($ch);
return $result;}
$token_slams = "Authorization: Bearer " . $access_token;
$authHeader = array(
$token_slams,
'Accept: application/form-data');
$schedule_path ='../../documents/' . $docs_record["document"];
$cFile = curl_file_create($schedule_path);
$post = array(
'old_record' => $old_record,
'employer_number' => $employer_number,
'payment_date' => $payment_date,
'fund_year' => $fund_year,
'fund_month' => $fund_month,
'employer_schedule'=> $cFile
);
send_curl_request_with_attachment("POST", $authHeader, $my_url, $post);

Categories