[Resolved] Binary data to PHP

Hello,was trouble processing the request from the screenshot code below. I could not access the image data. It’s not in _REQUEST or _POST. I finally found it in the $_FILES array.

Here is the contents of $_FILES[“fileUpload”]:
Key: name; Value: “fileUpload.png”
Key: type; Value: “image/png”
Key: tmp_name; Value: “C:\WINDOWS\Temp\phpE6F.tmp”
Key: error; Value: 0
Key: size; Value: 197964

// Saves screenshot as PNG file.
import System.IO;

// Take a shot immediately
function Start () {
UploadPNG ();
}

function UploadPNG () {
// We should only read the screen bufferafter rendering is complete
yield WaitForEndOfFrame();

// Create a texture the size of the screen, RGB24 format
var width = Screen.width;
var height = Screen.height;
var tex = new Texture2D (width, height, TextureFormat.RGB24, false);
// Read screen contents into the texture
tex.ReadPixels (Rect(0, 0, width, height), 0, 0);
tex.Apply ();

// Encode texture into PNG
var bytes = tex.EncodeToPNG();
Destroy (tex);

// For testing purposes, also write to a file in the project folder
// File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes);


// Create a Web Form
var form = new WWWForm();
form.AddField("frameCount", Time.frameCount.ToString());
form.AddField("Kamakazi","Ninja");
form.AddBinaryData("fileUpload",bytes);

// Upload to a cgi script 
var w = WWW("http://playcraftsystems.com/login/test/unity/makePNG.php", form);
yield w;
if (w.error != null)
	{
		print(w.error); 
	}
	else
	{
		print("Finished Uploading Screenshot"); 
	}
}

And the PHP to save a screenshot:

$myFile = $_FILES["fileUpload"]["tmp_name"];
$content = '';
$fh = fopen($myFile, 'r') or die("can't open file");
while (!feof($fh)) {
	$content .= fgets($fh);//filesize($myFile)) or die('can\'t read');
}
fclose($fh);


$myFile = "newOut.png";
$fh = fopen($myFile, 'w') or die("can't open file");
//$stringData = $_FILES["fileUpload"];
$stringData = $content;//"START:\n" . join(',\n',headerCustom()) . ' \END';
fwrite($fh, $stringData);
fclose($fh);

There might be some issues security-wise with this method, so I’ve opened a thread about mananging those:
http://forum.unity3d.com/viewtopic.php?p=386683#386683

2 Likes

wedstrom, 3 years, and you just saved my day! xD Thank you very much…
BTW for those getting “Recv failure: Connection was aborted” or “417 - Expectation Failed”, it only appears in the Editor, and probably only with AddBinaryData() usage. Compile it and run on server/local and everything should work fine, like here.
Regards.

hi @abgrac , i have to upload a PNG file to mysql database . how to send the binary data from unity(c-sharp) to php file and then from the php file to the database. I have a BLOB field in the table of the database to store binary data … please help.

1 Like