Codeigniter to Send form data to api url - php

I have form (5 fields which includes 1 file attachment field), whose field's data I need to submit on db as well as send on api url.
If I put api url in action of form tag then form data being send successfully. BUT I can't add api url in action coz like this form will redirect to that api url by leaving the site.
So to avoid putting api url in action I used following code to send form data to api url.
/* Endpoint */
$url = 'http://url_here';
$tmpfile = $_FILES['image']['tmp_name'];
$filename = basename($_FILES['image']['name']);
$data = array(
'to' => $to,
'cc' => '',
'message' => $subject,
'attachment' => '#'.$tmpfile.';filename='.$filename,
'message' => $message
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
/* Define content type */
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
/* Return json */
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
/* make request */
$result = curl_exec($ch);
/* close curl */
curl_close($ch);
echo $result;
This code giving this error.
{"timestamp":"2022-03-09T07:23:54.873+00:00","status":415,"error":"Unsupported Media Type","message":"","path":"/QRCodeGenerator/sendmail"}
While searching for solution, I also tried adding
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:application/json'));
For Accept:application/json to work I did convert array into json using jason_encode(). But it was still giving same error.
Where I am getting wrong?
UPDATE
I tried this code also which I got from postman where api working fine.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://url_here/QRCodeGenerator/sendmail',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array('to' => 'example#gmail.com','cc' => '','message' => 'This is test subject','body' => 'this is body msg','attachment'=> new CURLFILE('/path/to/file')),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
But this is giving blank page. $response printing nothing.

Related

How to setup correct cURL request for X Post? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have an API to track the shipment, the API request is below and worked well as excepted,
curl -X POST
--header '17token:xxxxxxxxxxxxxxxxxxxxxxxxx'
--header 'Content-Type:application/json'
--data '[{"number":"RR123456789CN"}]'
https://api.17track.net/track/v1/register
Here is my cURL code to get the response.
<?php
// started curl
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.17track.net/track/v1/register",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "number:RR123456789CN", // SOMETHING IS WRONG HERE.
//data '[{"number":"RR123456789CN"}]'
CURLOPT_HTTPHEADER => [
"17token:xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"header 'Content-Type:application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
The above code is showing error.
{"code":0,"data":{"errors":[{"code":-18010013,"message":"Submitted data is invalid."}]}}
I have tried all kinds of data structures like :
1. CURLOPT_POSTFIELDS => "RR123456789CN",
2. CURLOPT_POSTFIELDS => "[{number:RR123456789CN}]",
3. CURLOPT_POSTFIELDS => "{number:RR123456789CN}",
4. CURLOPT_POSTFIELDS => '{number:RR123456789CN}',
5. CURLOPT_POSTFIELDS => '{number:RR123456789CN}',
6. CURLOPT_POSTFIELDS => "data '[{number:RR123456789CN}]'",
7. CURLOPT_POSTFIELDS => "{\"number\": \"RR123456789CN\"}",
8. CURLOPT_POSTFIELDS => "[{\"number\": \"RR123456789CN\"}]",
but all the above data structures are failing and showing the same error.
I think I am doing something wrong with X POST / POST or
I am failing to request properly.
Edit
After doing some research I have written new code..
<?php
// setting the main url
$url = 'https://api.17track.net/track/v1/register';
// the tracking id as array
$post_data = array (
'number' => 'RR123456789CN',);
// start
$ch = curl_init();
// URL
curl_setopt($ch, CURLOPT_URL, $url);
// Returntransfer = true
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Post = true
curl_setopt($ch, CURLOPT_POST, 1);
// Header # 1
curl_setopt($ch, CURLOPT_HEADER, "17token:xxxxxxxxxxxxxxxxxxxxxxxxx");
// Header # 2
curl_setopt($ch, CURLOPT_HEADER, 'Content-Type:application/json');
// posting tracking id
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// Getting data in a string ($output)
$output = curl_exec($ch);
// error msg if fails
if ($output === FALSE){
echo "cURL Error:" . curl_error($ch);
}
// turning off the cURL
curl_close($ch);
// Printing the output.
print_r($output);
?>
Now i am getting {"code":401,"data":{"errors":[{"code":-18010002,"message":"Access token is invalid."}]}} error.
Note : Token is valid and correct, i think something is wrong with my code.
Thank you.
You have to send your data as raw body:
$curl = curl_init();
$data = array(0 => array("number" => "CM436202796IN"));
$data = json_encode($data);
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.17track.net/track/v1/register',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data, // Mistake is here
CURLOPT_HTTPHEADER => array(
'17token: xxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
replace
CURLOPT_CUSTOMREQUEST => "POST",
with just
CURLOPT_POST=>1
and replace
CURLOPT_POSTFIELDS => "number:RR123456789CN", // SOMETHING IS WRONG HERE.
with
CURLOPT_POSTFIELDS => json_encode(array(
0 => array(
"number" => "CM436202796IN"
)
)),
and replace
CURLOPT_HTTPHEADER => [
"17token:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"header 'Content-Type:application/json"
],
with
CURLOPT_HTTPHEADER => [
"17token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"Content-Type: application/json"
],

getting no errors with curl and also dont get any response

am trying to login to netflix using php curl but i get no response at all or errors.here is my code
$handle = curl_init();
$url = "https://www.netflix.com/ke-en/login";
// Array with the fields names and values.
// The field names should match the field names in the form.
$postData = array(
'userLoginId' => 'Lady',
'password' => 'Gaga',
'submit' => 'ok'
);
curl_setopt_array($handle,
array(
CURLOPT_URL => $url,
// Enable the post response.
CURLOPT_POST => true,
// The data to transfer with the response.
CURLOPT_POSTFIELDS => $postData,
CURLOPT_RETURNTRANSFER => true,
)
);
$data = curl_exec($handle);
echo curl_error($handle);
echo curl_errno($handle);
curl_close($handle);
echo $data;
the error i get is 0 and i saw that it means it is successfull

Using CURL to receive data, then send data to external webhook

so I am trying to receive JSON data from one webhook, use PHP to filter for some conditions, and then send the data to an external webhook address based on those conditions.
So for example, I created a php file on my server called "webhook.php":
$dataReceive = file_get_contents("php://input");
$dataEncode = json_encode($dataReceive, true);
print_r($dataEncode);
$curl = curl_init();
$opts = array (
CURLOPT_URL => 'https://hooks.zapier.com/hooks/catch/',
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $dataEncode,
CURLOPT_HTTPHEADER => array (
'Content-type: application/json'
)
);
curl_setopt($curl, $opts);
$results = curl_exec($curl);
echo $results;
curl_close($curl);
The "php://input" can either be exactly as it is, or I tried replacing it with the URL of my webhook.php file just in case. I can test my webhook using Postman, and I am returned a 200 OK, but the data is never sent to my external webhook (https://hooks.zapier.com/hooks/catch/).
I have written the conditional PHP code yet; I just want to ensure I can send and receive this data properly first. Any guidance is much appreciated!
Problem is with curl_setopt. You need to pass three argument for this method curl_setopt ( resource $ch , int $option , mixed $value ). You can set these by following
$curl = curl_init();
$opts = array (
CURLOPT_URL => 'https://hooks.zapier.com/hooks/catch/',
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $dataEncode,
CURLOPT_HTTPHEADER => array (
'Content-type: application/json'
)
);
foreach ($opts as $key => $value) {
curl_setopt($curl, $key, $value);
}
$results = curl_exec($curl);
echo $results;
curl_close($curl);
Or you can set them individually like this
curl_setopt($curl, CURLOPT_URL, 'https://hooks.zapier.com/hooks/catch/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
.....

VB to PHP Curl posting xml

I am trying to convert this VB script to PHP curl
xmlServerHttp.open "POST","url",False xmlServerHttp.setRequestHeader "Content-Type","application/x-www-form-urlencoded"
xmlServerHttp.send "xmlmessage=" & Server.URLEncode(xmlDocument)
‘ xmlDocument = the Xml Document contain the actual request
xmlServerStatus = xmlServerHttp.status
if xmlServerStatus = "200" then
xmlServerResponse = xmlServerHttp.responseText
Else
Response.Appendtolog ".xmlServer status is " & xmlServerStatus
end if
This is what I have so far however it is failing
$curl = curl_init(url);
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/x-www-form-urlencoded') ,
CURLOPT_POSTFIELDS => $xmldoc,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false
);
// Setting curl options
curl_setopt_array( $curl, $options );
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
// Getting results
echo curl_exec($curl);
The API i am calling return that the xmlmessage variable is not a valid xml document.
try to change $xmlDoc to $xmlDoc->asXML()
like this
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/x-www-form-urlencoded') ,
CURLOPT_POSTFIELDS => array('xmlmessage='=> $xmlDoc),
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false
);

cURL POST method not working

I am using cURL to call a REST API. And the below code works for GET method , but however for POST method call it doesn't work after i add :
curl_setopt($ch, CURLOPT_POST, true);
What could be the cause ?
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_SSL_VERIFYPEER => false, // Disabled SSL Cert checks
CURLOPT_HTTPHEADER => array('appId: C579929D-F0AA-4A8F-B6C6-1FF96694483C','appKey: AE78E7F1-FBDE-45F5-BAC2-210CEE9D3ED9')
);
$url = "some-url";
$ch = curl_init($url);
curl_setopt_array($ch, $options);
curl_setopt($ch, CURLOPT_POST, true);
$output = curl_exec($ch);
echo $output;
P.S
I double checked the API call using PostMan and it returns the expected result.
Do i need to add additional properties to API call ?
And i have to call REST API of format :
https://api.abc.com/v1/transactions/companyid/123/userid/456/description/ppeck/‌​source/PPA
And as suggested in the answer i have updated my code as :
$url = "https://api.abc.com/v1/transactions";
$ch = curl_init($url);
curl_setopt_array($ch, $options);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "companyid=12301&userid=31401&description=ppa-check&source=PPA&amount=123&txndate=010111&txntypeid=420&customerid=2701");
$output = curl_exec($ch);
And sadly it didn't worked.
try
post fields must be as a query string with appending (&) like
$url = 'http://example.com'; //your api call url
$fields = 'q=example&y=fgt&ghty'; // all posting fields separated with &
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

Categories