Using cURL how to post a file - php

I'm using AnonFiles website to upload files directly to my account using their API
https://anonfiles.com/docs/api
I created an account and they gave me a API key, and with this key I can upload straight into my account by appending for example ?token=5846e48082XXXXXX to the upload request.
Request Example
curl -F "file=#test.txt" https://api.anonfile.com/upload
Now i want a simple form with PHP code that allows me to pick a file and upload it to my anonfiles account.
Here is my try to write this request in PHP using cURL function
<?PHP
if (isset($_POST['submit'])) {
$url = 'https://anonfile.com/api/upload?token=5846e48082XXXXXX';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'file' => curl_file_create(
$_FILES['file']['tmp_name'],
$_FILES['file']['type'],
$_FILES['file']['name']
),
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$json = curl_exec($ch);
curl_close($ch);
$result = json_decode($json);
if (is_object($result) && $result->status) {
echo "OK!";
} else {
echo "Error";
}
}
?>
HTML FORM
<form action="' . $_SERVER['PHP_SELF'] . '" method="post" enctype="multipart/form-data">
File: <input type="file" name="file" id="file">
<br/>
<input type="submit" name="submit" id="submit" value="Send">
</form>
But this seems not working and print out Error message rather than ok and no file is uploaded.

You can do it like this:
<?PHP
if (isset($_POST['submit'])) {
$url = 'https://anonfile.com/api/upload?token=5846e48082XXXXXX';
$filename = $_FILES['file']['name'];
$filedata = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
if ($filedata != '')
{
$headers = array("Content-Type:multipart/form-data"); // cURL headers for file uploading
$postfields = array("filedata" => "#$filedata", "filename" => $filename);
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $postfields,
CURLOPT_INFILESIZE => $filesize,
CURLOPT_RETURNTRANSFER => true
); // cURL options
curl_setopt_array($ch, $options);
$json = curl_exec($ch);
$result = json_decode($json);
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
if ($info['http_code'] == 200) {
if (is_object($result) && $result->status) {
$msg = "OK!";
}
}
}
else
{
$msg = curl_error($ch);
}
curl_close($ch);
}
else
{
$msg = "Please select the file";
}
echo $msg;
}
?>

Related

How to Send automated SMS using API?

I have this condition to scheduled my sms. (ERROR) but the sms I'm using is POST method I need to be automated. And send sms to the number of the current id. I don't know how to get the number of the current id and send the message. Here is my code:
$duedate = "";
$date_now = date("Y-m-d");
date_default_timezone_set('Asia/Manila');
$date_now = strtotime($date_now);
$duedate = strtotime($duedate);
if ($duedate <= $date_now) {
function itexmo($number, $message, $apicode) {
$url = 'https://www.itexmo.com/php_api/api.php';
$itexmo = array('1' => $number, '2' => $message, '3' => $apicode);
$param = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($itexmo),
),
);
$context = stream_context_create($param);
return file_get_contents($url, false, $context);
}
if ($_POST) {
$number = $number;
$name = $name;
$api = "API";
$text = $name." : ".$number;
if (!empty($_POST['name']) && ($_POST['number']) && ($_POST['msg'])) {
$result = itexmo($number, $text, $api);
if ($result == "") {
echo "iTexMo: No response from server!!!
Please check the METHOD used (CURL or CURL-LESS). If you are using CURL then try CURL-LESS and vice versa.
Please CONTACT US for help. ";
} elseif ($result == 0) {
echo "Message Sent!";
} else {
echo "Error Num ". $result . " was encountered!";
}
}
}
}
It is better to use PHP cURL than stream_context_create and file_get_contents.
Take a look at below code, it should help you.
function itexmo($number,$message,$apicode)
{
$url = 'https://www.itexmo.com/php_api/api.php';
$postValues = http_build_query(['1' => $number, '2' => $message, '3' => $apicode])
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postValues);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"cache-control: no-cache",
"content-type: application/x-www-form-urlencoded"
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close ($ch);
return $response;
}
You can learn more PHP cURL.

Sending an Image to an API using Curl

I have been very frustrated in my attempt to send an image to an API using Curl. The image is coming from an html form from the clients end. When the form is submitted, I check to make sure the file is an image and the image is moved to an uploads folder as such:
$location = "ImageUploads/";
if(isset($_FILES["Image"]["tmp_name"]))
{
$checkImage = getimagesize($_FILES["Image"]["tmp_name"]);
if($checkImage !== false){
$Image = $_FILES['Image']['tmp_name'];
$ImageContent = addslashes(file_get_contents($Image));
$ImagePosted =true;
$ImageRealName = $_FILES['Image']['name'];
if(move_uploaded_file($Image, $location.$ImageRealName))
{
echo 'File Uploaded';
}
}
else{
echo 'Image not submitted';
}
After I move the image to an uploads folder, I initiate the curl Post as such:
$baseURL ="https://apithatIamusing.com/api/";
$curl = curl_init($baseURL);
$myImage = new CURLFile($location.$_FILES['Image']['name'],$_FILES['Image']['type'],$_FILES['Image']['name']);
After this, I create a curl_post_data array to include the rest of the api data requirements:
$curl_post_data = array(
'public_key' => $publicKey,
'private_key' => $privateKey,
'order_type' => 'Image',
'origin_id' => '11111111',
'name' => $FirstName,
'surname' => $LastName,
'photo' => $myImage);
I then set all of the Curtopts that I will be using:
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_UPLOAD, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
I then execute and attempt to decode the json response:
$imageResult= curl_exec($curl);
if($imageResult ===false)
{
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
$imageJson = json_decode($imageResult, true);
curl_close($curl);
$imageSuccess = $imageJson["success"];
$imageMessage = $imageJson["message"];
$imageSuccess = $imageJson["result"];
echo '<p>imageSuccess:'.$imageSuccess.' </p>';
echo '<p>imageMessage: '.$imageMessage.' </p>';
echo '<p>imageSuccess: '.$imageSuccess.' </p>';
I believe that the issue could be with the $myImage that curl is creating, the api documentation asks for the 'photo' to include the following information:
filename="t1.png"
Content-Type: image/png
But, to my understanding, curlfile is including, the name, content-type and the post name. Any recommendations or other methods to make this api post call using php would be greatly appreciated.

FB messenger Bot not getting postback payloads

I am developing a facebook chatbot. I am facing a issue which I cannot solve. I am developing this in laravel. Here I cannot get the postback payload. here is my code
public function index(Request $request) {
if ($request->hub_verify_token === $this->verifyToken) {
echo $request->hub_challenge;
exit;
}
$input = json_decode(file_get_contents("php://input"), true);
$senderId = $input['entry'][0]['messaging'][0]['sender']['id'];
$messageText = $input['entry'][0]['messaging'][0]['message']['text'];
$pageId = $input['entry'][0]['id'];
$accessToken = "access_token_that_got_from_fb";
//set Message
if($messageText != "") {
$answer = "Howdy! User";
}
if($messageText == "hello") {
$answer = 'Testing hello from bot';
}
foreach ($input['entry'][0]['messaging'] as $message) {
// When bot receive message from user
if (!empty($message['postback'])) {
$answer = 'got it tada';
}
}
//send message to facebook bot
$response = [
'recipient' => [ 'id' => $senderId ],
'message' => [ 'text' => $answer ] //json_encode($request->getContent())
];
$ch = curl_init('https://graph.facebook.com/v2.11/me/messages?access_token='.$accessToken);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$result = curl_exec($ch);
curl_close($ch);
}
and my route is
Route::any('chatbot', 'ChatbotController#index');
here the message is working . but the postback payload request is not going to server. on the other hand using the same code in normal php file I am able to get postback paylod.
$hubVerifyToken = 'chatbot';
$accessToken = "access_token";
// check token at setup
if ($_REQUEST['hub_verify_token'] === $hubVerifyToken) {
echo $_REQUEST['hub_challenge'];
exit;
}
// handle bot's anwser
$input = json_decode(file_get_contents('php://input'), true);
$senderId = $input['entry'][0]['messaging'][0]['sender']['id'];
$messageText = $input['entry'][0]['messaging'][0]['message']['text'];
$postback = isset($input['entry'][0]['messaging'][0]['postback']['payload']) ? $input['entry'][0]['messaging'][0]['postback']['payload'] : '' ;
//set Message
if($messageText == "hi") {
$answer = "Hello";
}
if($messageText == "hello") {
$answer = "Hello there, welcome to Chatleads";
}
if($postback) {
$answer = "postback TADA";
}
//send message to facebook bot
$response = [
'recipient' => [ 'id' => $senderId ],
'message' => [ 'text' => $answer ]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/v2.11/me/messages?access_token=$accessToken");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
How to solve this issue? can anyone show me a path?
Solved it by checking at laravel.log file.
$this->messageText = isset($this->input['entry'][0]['messaging'][0]['message']['text']) ? $this->input['entry'][0]['messaging'][0]['message']['text'] : '' ;
messageText should be like this. that's why its causing an error.

cUrl with json string and file upload

how do I have to "translate" the following curl command into a valid php curl function?
curl -X POST
-F "images_file=#fruitbowl.jpg"
-F parameters=%7B%22classifier_ids%22%3A%5B%22testtype_205919966%22%5D%2C%22threshold%22%3A0%7D
'https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key={key}&version=2016-05-20'"
It seems that I'm doing something wrong and I can't figure out the problem:
$method = 'POST'
$url = 'https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key=<myApiKey>&version=2016-05-20'
$data = array(
array(<file-information>),
array(<json-string>),
)
$header = array(
'Content-Type: application/json',
'Content-Length: ' . strlen(<json-string>),
)
)
public function send($method, $url, $data = null, $header = null)
{
$curl = curl_init();
switch ($method) {
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data) {
$postData = $this->renderPostData($data);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
}
break;
}
if($header) {
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl,CURLOPT_HTTPHEADER,$header);
}
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
}
protected function renderPostData($data)
{
$postData = array();
foreach ($data as $file) {
if ($file['isFile']) {
if(pathinfo($file['path'], PATHINFO_EXTENSION) == 'zip'){
$postData[$file['name']] = new \CURLFile($file['path'], 'application/zip', $file['name']);
}
else {
$postData[$file['name']] = new \CURLFile($file['path'], 'application/octet-stream', $file['name']);
}
} else {
// this contains the json encoded string
$postData[$file['name']] = $file['path'];
}
}
return $postData;
}
I tried several variations and the Watson Visual Recognition API error is now:
{
"custom_classes": 0,
"images": [
{
"error": {
"description": "Invalid image data. Supported formats are JPG and PNG.",
"error_id": "input_error"
}
}
],
"images_processed": 1
}
before it was:
{
"error": {
"code": 400,
"description": "Invalid JSON content received. Unable to parse.",
"error_id": "parameter_error"
},
"images_processed": 0
}
Thank you for your help!
My issue was this line:
$postData[$file['name']] = new \CURLFile($file['path'], 'application/zip', $file['name']);
the last parameter is the $postname. So to fix this issue I had to change this line to:
$postData[$file['name']] = new \CURLFile($file['path'], mime_content_type($file['path']), basename($file['path']));
and it worked - after I also removed the wrong $header completely
:)

Sending File with cURL

I've sent some post data with cURL and am now trying to send a file, getting lost along the way. I'm using a form with a file input. Then would like cURL to send it off to my server. Here is my upload page.
<form action="curl_page.php" method="post" enctype="multipart/form-data">
Filename: <input type="file" name="file" id="file" /> <br />
<input type="submit" name="submit" value="Submit" />
</form>
Here is my curl page with some issues.
<?php
$tmpfile = $_FILES['file']['tmp_name'];
$filename = basename($_FILES['file']['name']);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://my_server/file_catch.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'uploaded_file' => '#'.$tmpfile.';filename='.$filename,
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);
?>
The file_catch.php on my server looks like this.
<?php
$folder = "audio/";
$path = $folder . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['file']['name']). " has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
Thanks for any help!
You are not sending the file that you got through the post request. Use the below code for posting the file through CURL request.
$tmpfile = $_FILES['image']['tmp_name'];
$filename = basename($_FILES['image']['name']);
$data = array(
'uploaded_file' => '#'.$tmpfile.';filename='.$filename,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// set your other cURL options here (url, etc.)
curl_exec($ch);
For more reference check the below link
Send file via cURL from form POST in PHP

Categories