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);
Related
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.
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
So I uploaded on server an folder .zip using curl :
function uploadCurs(){
$ch = curl_init("http://myServer.com/service.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CUROPT_POSTFIELDS, "archive = ".NOM_OF_ARCHIVE);
echo curl_exec($ch);
}
Now, how to test if upload with succes and how to download this .zip?
Help me please!!! Thx in advance
You could use the file_exists function. See here for manual
You could do something like this:
<?php
$filename = '/path/to/foo.zip';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>
I am trying to upload images from client to server. My Client and server machines are separate so I need to send the image data from client to server.
My Client side php code goes like (Full client-side code):
$filename = $_FILES["fileToUpload"]["name"];
$filedata = $_FILES['fileToUpload']['tmp_name'];
$imagedata = file_get_contents($_FILES['fileToUpload']['tmp_name']);
$fields = array(
'filename' => $filename,
'filedata' => "#$filedata"
'imagedata' => "#$imagedata"
);
$field_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://10.2.16.102/temp.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_INFILESIZE, $filesize);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $field_string);
$server_output = curl_exec ($ch);
curl_close ($ch);
and my Server side code is (Full server-side code):
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
echo " and the filename is ". $_POST['filename'];
$uploadpath = "/uploads/";
$target_file = $_SERVER['DOCUMENT_ROOT']. $uploadpath . $_POST['filename'];
file_put_contents($target_file, $_POST['imagedata']);
//move_uploaded_file($_POST['filedata'],$target_file);
//copy($_POST['filedata'],$target_file);
?>
I am able to store the image in my uploads folder and the filesize is also the same but I am not able to see the image. The image viewer says "Couldn't load the png file". Do I have to convert the file into png format before storing. Also how to do that? Any help?
In a nutshell, I need a converter which can convert the file format into png or any other image format which can convert my file into an image at the server end.
Use $_FILES instead of $_POST in move_uploaded_file function e.g:
move_upload_file($_FILES[filedata][tmp_name], YOUR_PATH/$_FILES[filedata][name]);
Here's PHP doc:
http://php.net/manual/fr/function.move-uploaded-file.php
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.