yaron yaron - 1 year ago 95
C# Question

How do I put $_FILES content into binary var in PHP?

I have a unity C# program which is uploading a binary file (with some data).
(which is kind of irrelvant but maybe not)

var form = new WWWForm();
form.AddField("docid", "A");
byte[] textarr = Encoding.ASCII.GetBytes("just a sample text to be compressed and sent to server");
form.AddBinaryData("file", textarr,"file.tmp");
string req = "my url";
WWW www = new WWW(req,form);

I want to take the file content (as binary) so that I will be able to send into the database as binari in the PHP side.

I am trying to do something like this:

$binaridata = ~$_FILES["file"]["name"] (what do i need to do here? tried

file_get_content etc, but it always yield some errors)

Thanks for your help!

Answer Source
$binaryData = file_get_contents($_FILES['file']['tmp_name']);

The file is stored at the path indicated by tmp_name, name is just the name given by the client and practically irrelevant.

Depending on how you talk to the database and what database, you don't want to read the entire file contents into a variable though. For instance, using Postgres via PDO, you'd do this:

$stmt = $pdo->prepare('INSERT INTO ... VALUES (:file)');

$fh = fopen($_FILES['file']['tmp_name'], 'rb');
$stmt->bindParam(':file', $fh, PDO::PARAM_LOB);


The database adapter will read the file as a stream, which is much more economic than saving it in memory. Consult your database adapter's manual.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download