Php – Sending file contents in $_POST with PHP

filePHP

I'm developing a PHP script to send the content of a file from one script to another. In PHP usually it's used the $_FILE array that contains any uploaded file submitted in a form. But I didn't needed a form so I came up with something a little different:

// pseudo function names ahead

$content = file_get_contents(FILE_TO_SEND);
send_file_with_curl(base64_encode(gzcompress($content)));

So this basically fetches the content of the file, then compresses it with gzip compression and then base64 encodes it. Then everything is sent with a cURL POST request. On the other side I get sent content base64 decode it, uncompress it and everything comes back untouched.

So my question is: Is there any downside in doing things this way? Are there any security or integrity concerns I might be overlooking?

I forgot to mention that I also send an md5 digest of the file to check if the transfer went ok. And files to be sent will never be more than 3Mb of size.

Thanks in advance for all your answers.

Best Answer

I've found that the HTTP PUT method is nice for these kind of things. You surely don't need to encode the file, and most likely should not bother with compression, etc... There is no practical size limit to the following. It is fast and uses a fixed amount of memory regardless of the file size.


This function will HTTP PUT a file from the local disk to a remote URL

//Specify the location of a tmp file
function PutFile($sName, $sFile)
{
    $URL = "http://MY-SERVER/PutFile.php?FileName=" . urlencode($sName);

    $FILE = fopen($sFile, 'rb');

    $curl = curl_init($URL);
    curl_setopt($curl, CURLOPT_HEADER,0);
    curl_setopt($curl, CURLOPT_PUT, 1);
    curl_setopt($curl, CURLOPT_INFILE, $FILE);

    ob_start();
        curl_exec($curl);
        $sReturn = ob_get_contents();
    ob_end_clean();

    curl_close($curl);

    fclose($FILE);

    return $sReturn;
}

On the remote end, this is PutFile.php

<?php

$Name = (get and **validate** file name from $_GET['FileName'];
$Path = /somewhere/to/put/the/file/ + $Name

set_time_limit(3);

$f1 = fopen('php://input', 'rb');
$f2 = fopen($Path, 'wb');

while($data = fread($f1, 4096))
{
    fwrite($f2, $data);
}

fclose($f1);
fclose($f2);

echo "Success\n";

If you do not want to write it to disk, but work with it in memory, you could simply use file_get_contents('php://stdin').