I'm trying to run CURL command in PHP to upload image to an API
the code mentioned in the doc was:
curl -u 15:tokenkeyiskmzwa8awaa https://api.bukalapak.com/v2/images.json -F file=#product-image.png -X POST
Have tried using mac terminal running this curl command (with proper username and password) and successfully got the result as it is uploading, however was not successfully doing it on PHP.
My php code is :
<?php
$data = array('file'=> '#'.$imagePath );
// this is an absolute path, give something like D://folder/path/on/my/webserver/image.jpg
$user = '1234567';
$pass = '123456';
$ch = curl_init();
$curl_options[CURLOPT_URL] = 'https://api.bukalapak.com/v2/images.json';
$curl_options[CURLOPT_CAINFO] = storage_path('app/cacert.pem');
$curl_options[CURLOPT_HEADER] = "Content-Type: application/x-www-form-urlencoded";
$curl_options[CURLOPT_POST] = 1;
$curl_options[CURLOPT_USERPWD] = $user.':'.$pass;
$curl_options[CURLOPT_POSTFIELDS] = http_build_query($data);
curl_setopt_array($ch, $curl_options);
$content = curl_exec($->ch);`
Curl version : 7.47.1
PHP version : 5.6.21
any feedback is very appreciated.
You did not posted the complete script: $curl_options is undefined, storage_path is related to Laravel but there is no import, etc.
Something like the following script should work as you expect (I didn't tested it since I don't have an account on this service):
<?php
$imagePath = 'path/to/your/image.ext';
$user = 'youruser';
$pass = 'yourpass';
$file = curl_file_create($imagePath);
$body = ['file' => $file];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.bukalapak.com/v2/images.json');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, $user.':'.$pass);
curl_setopt($ch, CURLOPT_CAINFO, 'path/to/cacert.pem');
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$result = curl_exec($ch);
curl_close($ch);
Related
I'm recently started developing on moodle and one big problem is that whenever i build a plugin with a web page, it don't execute any of my curl commands, i hear that moodle has his own php library(an php file called filelib.php i suppose) with curl commands and i should be using its commands instead of mine, but i don't have much experience with moodle development and php so all that code make me very confused.
i tried this question before and a gentleman helped me with an example, i tried his code and it didn't work(it changed the output but still show an error message, i also tried changing the code to no avail) and i didn't get much of an explanation about how curl commands work on moodle(i'm still grateful for his help) or whats commands on filelib.php will substitue my code, can someone help me?
my code:
<?php
require_once(__DIR__.'/../../config.php');
require_once($CFG->libdir.'/filelib.php');
$PAGE->set_url(new moodle_url(url:'/local/iesde/selecionaraulas.php'));
$PAGE->set_context(\context_system::instance());
$PAGE->set_title('selecionar aulas');
$PAGE->requires->js_call_amd('local_iesde/tabelas', 'init');
echo $OUTPUT->header();
echo $OUTPUT->render_from_template('local_iesde/manageaulas', $templatecontext);
$api_server = 'url';
$api_http_user = 'user';
$api_http_pass = 'pass';
$key_acess = 'key';
$key_name = 'API-KEY';
$format = 'json';
$params = array(
'IDstudent' => 000000,
'IDcourse' => 000000,
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "{$api_server}/format/{$format}");
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($curl, CURLOPT_USERPWD, "{$api_http_user}:{$api_http_pass}");
curl_setopt($curl, CURLOPT_HTTPHEADER, array("{$key_name}:{$key_acess}"));
curl_setopt($curl, CURLOPT_NOBODY, 1);
curl_exec($curl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$output = curl_exec($curl);
var_dump(json_decode($output));
echo $output;
echo $OUTPUT->footer()
the purpose of this curl request is to print a list of ids that will be used on another curl request to generate a video file that will be executed on a videoplayer, the variables:
$api_server = 'url';
$api_http_user = 'user';
$api_http_pass = 'pass';
$key_acess = 'key';
$key_name = 'API-KEY';
$format = 'json';
$params = array(
'IDstudent' => 000000,
'IDcourse' => 000000,
);
Are all needed to execute the commands (one of the reasons i think the gentleman's example didn't work is that it didn't used all the variables of the code to get full validation).
well that is all, i'm very new to all of this so any explanation will help, thanks for the help.
I am trying to convert this curl request to php.
curl -X POST -F "file=#test_img.jpg" "http://127.0.0.1:5000/FileUploading/UploadImage/"test_img.jpg"
This request is working correctly with the following flask-RESTful code
class UploadImage(Resource):
def post(self, fname):
file = request.files['file']
if file:
# From flask uploading tutorial
filename = secure_filename(file.filename)
file.save(os.path.join("Images/", filename))
return jsonify({"Path": "Images/" + filename})
else:
# return error
return {'False'}
However, the following php curl request returns error 400 as it seems the request.files parameter is empty.
$file_name = "test_img.jpg";
$post_data = array(
"file" => "#" . $file_name,
"type" => 'image/jpg'
);
$ch = curl_init();
debug_to_console(http_build_query($post_data));
$host = "http://127.0.0.1:5000";
$url = $host . "/FileUploading/UploadImage/" . $file_name;
debug_to_console($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$file_param = 'file=' . $file_name;
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
$headers = array();
$headers[] = "Content-Type: multipart/form-data";
debug_to_console($headers);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
debug_to_console('Error:' . curl_error($ch));
}
curl_close($ch);
I don't know what i am doing wrong in this php request
first off, don't try to upload files using the # method, it was deprecated in PHP 5.5, disabled-by-default in PHP 5.6, and completely removed in PHP 7.0.0, in modern PHP, use CURLFile to upload files. also in line 10 you don't urlencode $file_name, that's a bug. and in line 17 you're trying to encode it to application/x-www-form-urlencoded-format (via http_build_query), but the command you're trying to convert is using multipart/form-data-format, when you give CURLOPT_POSTFIELDS a string (as returned by http_build_query), curl will send it as application/x-www-form-urlencoded by default but to make curl send it in multipart/form-data-format (as you want), set CURLOPT_POSTFIELDS to an array, not a string, and curl will send it in multipart/form-data.
The main problem that i've to do is sending an image from another server to AWS after some process. For that i've done the database processes in the first server. It works very well, i tested it. After that i've to send this image directly to AWS to start another .php file. I try it via cURL function:
server1.php the php file that's found in the first server:
$url = 'http://myawsurl.com/server/test.php';
$imageData = file_get_contents($_FILES['fileToUpload']['tmp_name']);
$post_data = array(
'tmp' => $_FILES["fileToUpload"]["tmp_name"],
'type' => $_FILES["fileToUpload"]["type"],
'name' => $_FILES["fileToUpload"]["name"],
'data' => $imageData
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
print_r($output);
test.php the php file that's found in aws:
if ($_POST["tmp"] && $_POST["name"] && $_POST["type"] && $_POST["data"]) {
$target_dir_requests = "/requests/";
create_folder_if_not_exist(ABSPATH . $target_dir_requests);
$dir_for_req_server = ABSPATH . $target_dir_requests . basename($_FILES["fileToUpload"]["name"]);
$dir_for_req_server = base64_to_jpeg($_POST["data"],$dir_for_req_server);
// After some requests that i've to do and i've done
} else {
echo "data sending error";
}
i tried something for todo but they did not work. Could you please help me for find a solution ? Thanks.
You are checking if the variable is true or not with the if($_POST[])
What you actually want is to check if the variable isset
Try this and see if you get any result:
if(isset($_POST['tmp'])){
echo 'test';
}
Or
$tmp = isset($_POST['tmp']) ? trim($_POST['tmp']) : null;
if(!empty($tmp)){
echo 'test';
}
The curl itself should be working
Please am creating a web application that sends sms alert when a user is registered. i wrote the script to do that which is below, i then uploaded that file to my web server for testing but it refuse to work. am actually having issues understanding curl. can someone tell me what am not doing right?
<?php
$number='08166848961';
$message_body='my test from server';
echo CURLsendsms($number,$message_body);
function CURLsendsms($number, $message_body){
$type='0';
$routing='3';
$token = 'VMnzTxbzgFKs5Po2vt6BhVt6VSWWNSDuaKAeI4Nch2cL4USf6furZ7ckVSc4Qf8jk';
$api_params ='message='.$message_body.'&to='.$number.'&sender='.$number.'&type='.$type.'&routing='.$routing.'&token='.$token;
$smsGatewayUrl = "https://smartsmssolutions.com/api/?";
$smsgatewaydata = $smsGatewayUrl.$api_params;
$url = $smsgatewaydata;
$ch = curl_init(); // initialize CURL
curl_setopt($ch, CURLOPT_POST, false); // Set CURL Post Data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch); // Close CURL
// Use file get contents when CURL is not installed on server.
if(!$output){
return $output = file_get_contents($smsgatewaydata);
}else
}
?>
I am using cURL for the first time. I have to send one image file and one audio file posted by the user.
My cURL code is working, but instead of an image file and an audio file my code is sending a .tmp file.
I googled it, but in every example I found they have used realpath of file directly.
I tried to find real path of the file, but I didn't find any solution.
Here is my code block in which I am collecting all data in an array to pass it to cURL:
$name = $_POST['name'];
$image = $_POST['image']['name'];
$imagetmp = $_POST['image']['tmp_name'];
$imagesize = $_POST['image']['size'];
$imagepath = '#'.$imagetmp;
$audio = $_POST['audio']['name'];
$audiotmp = $_POST['audio']['tmp_name'];
$audiosize = $_POST['audio']['size'];
$audiopath = '#'.$audiotmp;
$data = array("name" => $name, "image"=> $imagepath, "audio" => $audiopath); //array to sned data using cURL
//my cURL code to post data
Where am I doing wrong? How to send files using cURL?
This is what I used to post file data:
$filedata = file_get_contents('file_location/filename.jpg');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $filedata);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/octet-stream'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$return = curl_exec($ch);
curl_close($ch);
You can use file=#path with curl
curl -kiSs -X POST https://<domain>/path/to/api/files/ \
-F "param1=param2" \
-F "file=#/path/to/test.xlsx" \
-H "Authorization":"bearer eyJhbGciOiJIUzI1NiIsIn"
File successfully uploaded (test.xlsx!)