For me, it was required to send a uploaded file on application server to web server So, I googled, tested and implemented this solution. Basically, this is not purely my work as usual as.

First, make sure CURL is installed on your PHP. Installation might be different according your setup.

From Server will have a page like as below with form and codes, sending file with CURL.

[code language=”php”]
<?php
function curlUpload($file){
$handler = "http://www.sample.com/handler.php";
$dest = "test/files/";
$fp = fopne($file, "r");
$data = fread($fp, filesize($file));
$POST_DATA = array( ‘dest_dir’ => $dest,
‘file_name’=> basename($file),
‘file’=>base64_encode($data)
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $handler);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $POST_DATA);
$response = curl_exec($curl);

curl_close ($curl);
fclose($fp);
}

// Uploading Problem
if ( move_uploaded_file($_FILES["myFile"]["tmp_name"], $temp_path . basename($_FILES["myFile"]["name"]))){
curlUpload($temp_path . basename($_FILES["myFile"]["name"]));
} else {
echo "Return Code: " .$_FILES["myFile"]["error"];
}
[/code]

$POST_DATA can contain any text data you would like to send along with file data. base64_encode is used to convert binary data to text data since only text data can be sent and received between client and server without reloading web pages.

HTML code on from server may look like as below

[code language=”html”]

<form>
<input type="file" name="myFile" id="myFile" size="70"/>
<input type=submit value="Send">
</form>

[/code]

To Server will need handler.php as below on the right directory. For example it should be in the root directory for this sample code. This page just get $_POST data and stores a received file in the destined directory.

[code language=”php”]

<?php
$encoded_file = $_POST[‘file’];
$file_name = $_POST[‘file_name’];
$dest_dir = $_POST[‘dest_dir’];
$decoded_file = base64_decode($encoded_file);
file_put_contents("./".$dest_dir.$file_name, $decoded_file); ?>

[/code]

Please make sure the ownership of destination directory and handler.php to set to your web/http server. It is www-data:www-data for Ubuntu Apache for example.

 

Leave a Reply

Your email address will not be published. Required fields are marked *