I've been trying to upload a file to a remote API via CURL for the past few days with little luck, The code works perfectly on windows, and I get the desired returned output back from the API.
My issue is that once I move to a linux environment and I upload the file via CURL I get the error message below.
What I tried:
I thought perhaps permissions and the likes were the cause of my problem as it was saying that it cannot find the file, so I decided to modify my code slightly to upload to the server, move it into an upload folder then pick that file to send via curlfile but still no luck. Here is the error I'm getting:
"errors": [
{
"developerMessage": "Error while manipulating file /home/USER/public_html/top/tmp/client17.jpg due to a File system / Amazon S3 issue /usr/share/tomcat7/.fineract/top/documents/clients/1/8q9sr/home/USER/public_html/top/tmp/client17.jpg (No such file or directory)",
"defaultUserMessage": "Error while manipulating file /home/USER/public_html/top/tmp/client17.jpg due to a File system / Amazon S3 issue /usr/share/tomcat7/.fineract/top/documents/clients/1/8q9sr/home/USER/public_html/top/tmp/client17.jpg (No such file or directory)",
"userMessageGlobalisationCode": "error.msg.document.save",
"parameterName": "id",
"value": null,
"args": [
{
"value": "/home/USER/public_html/top/tmp/client17.jpg"
},
{
"value": "/usr/share/tomcat7/.fineract/top/documents/clients/1/8q9sr/home/USER/public_html/top/tmp/client17.jpg (No such file or directory)"
}
]
}
]
Here the code that I am using:
// UPLOAD NEW FILES
if(ISSET($_FILES))
{
$uploads = array('guarantor_id_card', 'guarantor_payslip_1', 'guarantor_payslip_2', 'guarantor_payslip_3', 'guarantor_bank_1', 'guarantor_bank_2','guarantor_bank_3' );
$postFields = array();
// for creating documents
foreach($uploads as $k => $v)
{
// GET UPLOAD NAME FROM ARRAY
$upload_name = $v;
if(empty($_FILES[$upload_name]['error']))
{
$uploaddir = getcwd() . "/tmp/";
$uploadfile = $uploaddir . basename($_FILES[$upload_name]['name']);
if (move_uploaded_file($_FILES[$upload_name]['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
//files
$postFields['file'] = new CURLFile($uploadfile);
//metaData USING COUNTER AND UPLOAD NAME DYNAMIC
$postFields['fileName'] = $_FILES[$upload_name]['name'];
$postFields['type'] = $_FILES[$upload_name]['type'];
$postFields['name'] = 'Supporting Docs';
$postFields['description'] = $_FILES[$upload_name]['name'];
// initialise the curl request
$request = curl_init("https://APIURL_HERE");
// send a file
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_USERPWD, $user . ":" . $password);
curl_setopt($request, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
curl_setopt($request, CURLOPT_PORT, 8443);
curl_setopt($request, CURLOPT_SAFE_UPLOAD, TRUE);
curl_setopt($request, CURLOPT_POSTFIELDS, $postFields);
// output the response
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
curl_setopt($request, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($request, CURLOPT_SSL_VERIFYPEER, 0);
$send_request = curl_exec($request);
// close the session
curl_close($request);
echo $send_request;
}
}
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print_r(getcwd());
echo '<br>';
print_r($uploadfile);
print "</pre>";
}
I'm out of ideas, if anyone has experience in this please do help!
Thanks.
Related
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.
I tried to download a file via Icecat. The file need an access to be downloaded.
My problem is :
the file_get_content does'nt download the file. My directory is on 777 and the path is correct.
if I insert the document inside the directory, the file is not unzipped.
public function getIceCatFile() {
set_time_limit (0);
$url = 'https://data.Icecat.biz/export/freexml/EN/daily.index.xml.gz';
$context = stream_context_create(array('http' => array( 'header' => "Authorization: Basic " . base64_encode($this->username . ":" . $this->password) )));
if ($this->checkDirectoryIceCat() === true) {
// does'nt download the file inside the server directory
file_get_contents($url, true, $context);
$file = $this->IceCatDirectory . 'daily.index.xml.gz';
if (is_file($file)) {
$zip = new \ZipArchive;
// error failed same if I include the file inside the directory
$icecat_file = $zip->open($this->IceCatDirectory . 'files.index.xml.gz');
if ($icecat_file === true) {
$zip->extractTo($icecat_file);
$zip->close();
echo 'file downloaded and unzipped';
} else {
echo 'failed';
}
} else {
echo 'error no file found in ' . $file;
}
}
}
Make a try like this to download file that has username and password authentication using PHP Curl,
$localfile = fopen($file_store_locally, 'wb'); // open with write enable
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $localfile);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "username:password"); // see here for auth
curl_exec($ch);
curl_close($ch);
fclose($localfile); //store file data to local file
I'm having difficulty uploading a .csv file through a cURL request to a RESTful API. I'm receiving a successful response (200 OK) but no data appears to be submitted:
{
"meta": [
],
"code": 200,
"object": "csvfile",
"data": [
],
"time": 1472464675
}
This is being made with the following request. I've added commenting to break down each of the CURL_SETOPTS:
// create a CURLFile object
$cfile = curl_file_create($fileName,'text/csv', $fileName);
// start curl request
$curl = curl_init();
// assign POST data
$data = array('file' => $cfile);
// specify POST request
curl_setopt($curl, CURLOPT_POST, true);
// basic auth
curl_setopt($curl, CURLOPT_USERPWD, getenv('USERNAME').':'.getenv('PASSWORD'));
// destination URI
curl_setopt($curl, CURLOPT_URL, 'https://api.arestfulapi.com');
// associate curlfile
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
// since we're using PHP 5.6 we need to enable CURLOPT_SAFE_UPLOAD
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
// return options
curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_STDERR, $out);
$response = curl_exec($curl);
$err = curl_error($curl);
// debugging
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo("CURL RESPONSE: ");
echo $response;
}
curl_close($curl);
I should mention I don't fully understand the importance of the $postname field in CURLfile objects. Furthermore I'm not entirely sure what I'm doing by assign POST data as demonstrated in the construct's documentation (http://php.net/manual/en/class.curlfile.php).
Note: I'm writing this in a Laravel application and am aware of the Guzzle client but have opted to present the problem this way, as there's more support for typical cURL problems on SO. I believe the issue is something to do with my cURLfile creation but have spent hours trying to pinpoint it.
What could be causing this issue?
I found a solution . I reworked the request using the Guzzle client again and eventually had success. Here's a copy of my solution:
// instantiate Guzzle http request
$client = new \GuzzleHttp\Client();
// provide an fopen resource
$filepath = 'public/'.$fileName;
$body = fopen($fileName, 'r');
// make the request
$res = $client->request('POST', 'https://api.website.com', [
'auth' => [
getenv('USERNAME'),
getenv('PASSWORD')
],
'body' => $body
]);
echo ("STATUS CODE: ");
echo $res->getStatusCode();
// 200
How can I upload a file, either by using cURL or anything else, in PHP?
In other words, the user sees a file upload button on a form, the form gets posted to my PHO script, then my PHP script needs to re-post it to another script (eg on another server).
I have this code to receive the file and upload it:
echo"".$_FILES['userfile']."";
$uploaddir = './';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if ( isset($_FILES["userfile"]) ) {
echo '<p><font color="#00FF00" size="7">Uploaded</font></p>';
if (move_uploaded_file
($_FILES["userfile"]["tmp_name"], $uploadfile))
echo $uploadfile;
else echo '<p><font color="#FF0000" size="7">Failed</font></p>';
}
How can I send the file to the receiver server?
Use:
if (function_exists('curl_file_create')) { // php 5.5+
$cFile = curl_file_create($file_name_with_full_path);
} else { //
$cFile = '#' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);
You can also refer:
http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/
Important hint for PHP 5.5+:
Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
I am going to have a php that upload json to the web.
Here is my file to upload (located in my local drive)
test.php
$string = file_get_contents("results.json");
$ch = curl_init();
$post_values = array('json_data' => $string);
curl_setopt($ch, CURLOPT_URL, '<dir path>/test1.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_values);
$data = curl_exec($ch);
if (!curl_errno($ch)) {
echo 'Received raw data' . $data;
}
curl_close($ch);
?>
This is the code to get the posted json
test1.php
<?php
$data = json_decode($_POST['json_data'], true);
header('Content-type: text/json');
foreach ($data['queue'] as $queue) {
echo "Wof = " . $queue['wof'];
echo "Input Date = " . $queue['input_date'] . "<br />";
}
?>
Both code works well.
But when I upload test1.php to the web server, it means I send my json located in my computer to the server. I doesn't work.
No Error msg I get, only it does not show the data. only show Received raw data
My question is : How to fix it?, is there something wrong with my code?
Thanks in advance.