Save an image from Flash in PHP

How to save binary data from a flash application in PHP?

For example the flash application will send a .png file in a similar way like this:
Flash code…..

1
2
3
4
5
6
7
8
9
import org.bytearray.encodage.images.PNGEncoder  ;
var dataPngBitmap:BitmapData = new BitmapData ( 320, 240, false, 0x990000 );
var binaryFeedPNG:ByteArray = PNGEncoder.encode ( dataPngBitmap );
var HTTPheader:URLRequestHeader = new URLRequestHeader ("Content-type", "application/byte-stream");
var request:URLRequest = new URLRequest("http:www.mywebsite.com/saveimage.php?name=myimage.png");
request.requestHeaders.push(HTTPheader);
request.data = binaryFeedPNG;
request.method = URLRequestMethod.POST;
navigateToURL(request, "_blank");

To save the file in PHP you need the following code in your saveimage.php file:

1
2
3
4
5
6
7
if (isset ( $GLOBALS ["HTTP_RAW_POST_DATA"] )) {
$file = $GLOBALS ["HTTP_RAW_POST_DATA"];
$filename = $_GET['name'];
$fp = fopen ( $filename, 'wb' );
fwrite ( $fp, $file );
fclose ( $fp );
}

In this example we write the file based on the filename that is provided in the url: “myimage.png”.
Please be very careful with this:

  • You have no way to be sure that this is in fact a png file.
  • You could overwrite an existing file.
  • Someone could try to overwrite an existing php file: e.g. what happens when someone provide this name: “../../index.php”?

If you you need name information from the flash application, do some checks on the filename:

  • Is the extension allowed?
  • Does it contain prefixed dots, slashes etc.?

But it is always safer to provide the the image name yourself and always control the path and file extension of the file you will be writing.

Related posts

Tags: ,

Leave a Reply