I am writing a PHP script that passes a file and a bunch of parameters to upload.php
.
Here is a snippet of upload.php
if (!empty($_FILES["Image"])) {
$user_id = $_POST["user_id"];
$user_name = $_POST["user_name"];
$file_name = $_FILES["Image"]["name"];
}
I am trying to send a curl
request which passes those parameters.
function post($file) {
$url = 'http://localhost/mc/upload.php';
$fields = array(
'user_id' => "test_id",
'user_name' => "test_user",
'Image' => '@' . $file
);
$fields_string = "";
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
The file is sent as a $_POST and not in $_FILES. Also what I sent is received as a string in $_POST['Image']
I have tried using the answer given in this post here
if (function_exists('curl_file_create')) {
$cFile = curl_file_create($file_name_with_full_path);
} else {
$cFile = '@' . realpath($file_name_with_full_path);
}
Using the above snippet to prepare the file before sending it. Since I am using PHP version 5.5+ an object is created. It gives the following error
Object of class CURLFile could not be converted to string
This error happens when I am concatenating all the parameters to $fields_string