PHP's $HTTP_RAW_POST_DATA in ASP - php

I'm updating a classic asp page with a flash app and I need to reproduce the PHP's $HTTP_RAW_POST_DATA function under vbscript (OR C# .NET since it's on IIS7 also). This is what I have so far but does not work. The browser just tells me that it can not display the image because of errors or corruption. Thanx in advance.
AS3 Code
vid_out = new Video();
vid_out.x = 0;
vid_out.y = 0;
vid_out.width = cam.width;
vid_out.height = cam.height;
vid_out.attachCamera(cam);
addChild(vid_out);
var bitmapData:BitmapData = new BitmapData(640, 480);
bitmapData.draw(vid_out);
var encoder:JPGEncoder = new JPGEncoder();
var byteArray:ByteArray = encoder.encode(bitmapData);
var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
var jpgURLRequest:URLRequest = new URLRequest("/capture.asp?i=blah.jpg");
jpgURLRequest.requestHeaders.push(header);
jpgURLRequest.method = URLRequestMethod.POST;
jpgURLRequest.data = byteArray;
navigateToURL(jpgURLRequest, "_blank");
non-working vbscript code
Function RSBinaryToString(xBinary)
Dim Binary
If vartype(xBinary)=8 Then Binary = MultiByteToBinary(xBinary) Else Binary = xBinary
Dim RS, LBinary
Const adLongVarChar = 201
Set RS = CreateObject("ADODB.Recordset")
LBinary = LenB(Binary)
If LBinary>0 Then
RS.Fields.Append "mBinary", adLongVarChar, LBinary
RS.Open
RS.AddNew
RS("mBinary").AppendChunk Binary
RS.Update
RSBinaryToString = RS("mBinary")
Else
RSBinaryToString = ""
End If
End Function
photoname = trim(request.querystring("i"))
Dim ByteCount, BinRead
ByteCount = Request.TotalBytes
If ByteCount > 0 Then
BinRead = Request.BinaryRead(ByteCount)
Response.ContentType = "image/jpeg"
Response.AddHeader "Content-Disposition", "inline; filename=" & photoname
Response.BinaryWrite(RSBinaryToString(BinRead))
Response.End()
End If
'working vbscript code
I'm just using the actual folder path located on the server. You can user servermappath also.
photoname = trim(request.querystring("i"))
folder = "C:\some_folder\"
tofolder = folder & photoname
Dim BinaryData, ByteCount
ByteCount = Request.TotalBytes
BinaryData = Request.BinaryRead(ByteCount)
Set objADO = Server.CreateObject("ADODB.Stream")
objADO.Type = 1
objADO.Open
objADO.Write BinaryData
objADO.SaveToFile tofolder, 2
Set objADO = Nothing

See Request Object reference
Specifically, you will be interested in Request.TotalBytes property to get request body size and Request.BinaryRead method to read the request body.
Quote from MSDN:
VBScript
<%
Dim vntPostedData, lngCount
lngCount = Request.TotalBytes
vntPostedData = Request.BinaryRead(lngCount)
%>

Related

AS3 RSAKey.sign() != PHP openssl_sign()

everyone!
I have some PHP code to sign some text and it works fine. I need to have equivalent of this code on actionscript 3. I need your help.
$privateKeyPath = "private.key";
$message = "hello";
$privateKey = file_get_contents($privateKeyPath);
openssl_sign($message, $signature, $privateKey);
echo base64_encode($signature);
In AS3 I using as3crypto library to make sign:
private function readPrivateKey():String {
var f:File = new File("/Users/ivan/Desktop/private.key");
var fs:FileStream = new FileStream();
fs.open(f,FileMode.READ);
var key:String = fs.readUTFBytes(fs.bytesAvailable);
fs.close();
return key;
}
private function getSign():void {
var message:String = "hello";
var privateKey:String = readPrivateKey();
var srcBA:ByteArray = new ByteArray();
var resultBA:ByteArray = new ByteArray();
var rsaKey:RSAKey;
var base64encoder:Base64Encoder = new Base64Encoder();
srcBA.writeUTFBytes(message);
rsaKey = PEM.readRSAPrivateKey(privateKey);
rsaKey.sign(srcBA, resultBA, srcBA.length);
b64encoder.encodeBytes(resultBA);
trace(b64encoder.toString());
}
I have same private key file. I expect that the output values are equals. But these values are different =(
What am I doing wrong?
UPDATE: I tried to verify my encoded base64 string using public key and verify method - everything is ok inside Actionscript.
Example:
var text:String = "hello";
var srcBA:ByteArray;
var desBA:ByteArray;
var rsaKey:RSAKey;
var encodedB64:String;
// ENCODING
srcBA = new ByteArray();
srcBA.writeUTFBytes(text);
desBA = new ByteArray();
rsaKey = PEM.readRSAPrivateKey( readPrivateKey() );
rsaKey.sign(srcBA, desBA, srcBA.length);
encodedB64 = Base64.encodeByteArray(desBA);
trace("Original: " + text);
trace("Encoded: " + encodedB64 );
// DECODING
var srcBA2:ByteArray = new ByteArray();
var desBA2:ByteArray = new ByteArray();
var rsaKey2:RSAKey = PEM.readRSAPublicKey( readPublicKey() );
srcBA2 = Base64.decodeToByteArray( encodedB64 );
rsaKey2.verify(srcBA2, desBA2, srcBA2.length);
trace("Decoded: " + desBA2.toString() );
My original text and decoded value are equals. So, I conclude that AS3 signing methods are different than PHP.
Is anyone have idea to make it equals?
Thanks.
Maybe it's late answer, but anyway...
AS3 works fine in your second code, PHP needs some tweaks, like this:
$privateKeyPath = "private.key";
$message = "hello";
$privateKey = openssl_pkey_get_private(file_get_contents($privateKeyPath));
openssl_private_encrypt($message, $signature, $privateKey);
echo base64_encode($signature);
I just checked with key genereted on this site:
http://www.selfsignedcertificate.com/ and everything works fine, I'm getting similar results in both PHP and AS3 versions.

Sending and Recieving PNGencoded to php mysql BLOB

I'm trying to send encoded data for a bitmap image to a server and back to the( or a separate) client. There's probably an easier way to do this with sockets or something, but I'm a very casual and still a pretty new programmer and I had trouble understanding other methods. The encoding and decoding works fine and I can save and open up the encoded png, but somewhere on the php/mysql side the encoded data loses most of it's code.
Actionscript code for sending the encoded data to the php.
var req:URLRequest = new URLRequest("http://host.net//img.php");
req.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader;
var phpvar = new URLVariables();
var shape:MovieClip = new MovieClip();
shape.graphics.beginFill(0xFF0000);
shape.graphics.drawRect(0, 0, 100, 100);
addChild(shape);
var bmp:BitmapData = new BitmapData(500, 350);
bmp.draw(shape);
var byte:ByteArray = new ByteArray();
bmp.encode(new Rectangle(0,0, 100, 100), new flash.display.PNGEncoderOptions(false), byte);
//save on database
phpvar.bytez = byte;
req.data = phpvar;
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(req);
trace(req.data.bytez);
The traced output is:
PNG
->
IHDRddÿIDATxÚíÐ1 µçYÁÏ"Ð)®F,Y²dɒ¥#,Y²dÉR
K,Y²d)%K,Y²Ȓ%K,Y dɒ%K,²dɒ%KY²dɒ%K,Y²dɒ¥#,Y²dÉR
K,Y²d)%K,Y²Ȓ%K,Y dɒ%K,²dɒ%KY²dɒ%K,Yß^Çjú··IEND®B`
Actionscript code for recieving data:
var req = new URLRequest("http://host.net//imgsend.php");
var loader = new URLLoader(req);
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, onComplete);
loader.load(req);
function onComplete(e:Event) {
var loaderer:Loader = new Loader();
var byte:ByteArray = new ByteArray()
byte = e.target.data;
trace(byte);
}
Traced output is:
PNG
->
For some reason it knows the encoded data is for a PNG, but all there is is a header. I think the problem is in my php/mysql code, but I'm not completely sure here. I'm using a free webhosting service with phpMyAdmin for convenient sake, the Images table is just a BLOB column and the php files are uploaded on the host server.
PHP code for reading and inserting into mysql (img.php)
<?php
mysql_connect($mysql_host, $mysql_user, $mysql_password);
mysql_select_db($mysql_database) or die(mysql_error());
$pic = $_POST['bytez'];
$sql = "INSERT INTO Images (img) VALUES ('$pic')";
mysql_query($sql);
?>
PHP code for taking the data form the server and sending it to Actionscript (imgsend.php)
<?php
mysql_connect($mysql_host, $mysql_user, $mysql_password);
mysql_select_db($mysql_database) or die(mysql_error());
$sql = "SELECT * FROM Images";
$records = mysql_query($sql);
while($byte=mysql_fetch_assoc($records)){
echo $byte['img'];
}
?>
I didn't necessarily find an answer to this exact method, but I found an alternate solution, ie writing the file directly into the directory. From what I've read this is much more efficient anyways. The code is basically the same only I added URLcontentType and extended the URL for the URL request address for the file's location.
var req:URLRequest = new URLRequest("http://host.net//img.php?filename=something.png");
req.method = URLRequestMethod.POST;
req.contentType = "application/octet-stream";
var loader:URLLoader = new URLLoader;
var shape:MovieClip = new MovieClip();
shape.graphics.beginFill(0xFF0000);
shape.graphics.drawRect(0, 0, 100, 100);
addChild(shape);
var bmp:BitmapData = new BitmapData(500, 350);
bmp.draw(shape);
var byte:ByteArray = new ByteArray();
bmp.encode(new Rectangle(0,0, 100, 100), new flash.display.PNGEncoderOptions(false), byte);
//save on database
req.data = byte;
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(req);
The PHP code is for img.php is:
<?php
$fileName = $_GET['filename'];
$fp = fopen( $fileName, 'wb' );
fwrite( $fp, $GLOBALS['HTTP_RAW_POST_DATA'] );
fclose( $fp );
?>
Loading the file is simple, not going to bother posting that. I'll deal with unique file names on my own, baby steps. Thanks for helping me talk this out some!

Upload image by AIR app

Have an issue with Air application and upload the image to server by php.
What I'm doing wrong? On progress everything is alright, is showing progress and response, but php can't find an image.
var request:URLRequest = new URLRequest("http://xxxxxxxxxx/api.php");
request.method = URLRequestMethod.POST;
request.contentType = "application/octet-stream";
var variables:URLVariables = new URLVariables();
variables.action = "addEntry";
variables.user = "1";
request.data = variables;
var file:FileReference = new FileReference();
var filenameSmall:String = "xxxxx/" + _userName+"/thumbnail.jpg";
if(_fb == true)
{
filenameSmall = "xxxxx/" + user +"/thumbnail.jpg";
}
file = File.desktopDirectory.resolvePath( filenameSmall );
file.addEventListener(ProgressEvent.PROGRESS, uploadProgress);
file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadDataComplete);
file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, uploadError);
file.addEventListener(HTTPStatusEvent.HTTP_STATUS, uploadError);
file.addEventListener(IOErrorEvent.IO_ERROR, uploadError);
file.upload(request, "image");
The upload of file reference could not send any request or variables to php files. It just upload the file to the path you have given in the url. If you want to save an image using php
you should convert the image to byte array,
Do any one the encoding process(either PNGEncoding or JPEGEncoding),
If you want then do any standard encoding(base64) for security
Then send that string to php
Make your php file to read that data and write it.

uploading image and php POST method in windows phone

this is my first post. please be kind :)
i'm trying to get picture from media library (in WP 7), upload it using httpwebrequest, and save it to folder in the server. i succeed to convert the image to string of byte (but i suspect there are something wrong here), send the string using POST, and retrieve it in my php web page.
Everything seems to be working well, but when i convert the string of byte to jpeg (using imagecreatefromstring function) it always come up empty picture. here is my code in C# and php. I'm sorry for my English if it's not perfect (or far from perfect) :)
this is my c# code along with some comments
public partial class MainPage : PhoneApplicationPage
{
string uploadUri = #"http://192.168.138.1/meeshot/upload.php"; //php web page for retrieve and saving file in the server
string requestImageName = "picture"; //variable name for post ---- >$_POST['picture']
string postdata; //byte data generate using BitmapToByte function
// Constructor
public MainPage()
{
InitializeComponent();
}
PhotoChooserTask selectphoto = null;
Image image1 = new Image ();
private void button1_Click(object sender, RoutedEventArgs e) //user choosing photo from media library
{
selectphoto = new PhotoChooserTask();
selectphoto.Completed += new EventHandler<PhotoResult>(selectphoto_Completed);
selectphoto.Show();
}
void selectphoto_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BinaryReader reader = new BinaryReader(e.ChosenPhoto);
image1.Source = new BitmapImage(new Uri(e.OriginalFileName));
HttpWebRequest req = HttpWebRequest.Create(
new Uri(this.uploadUri)) as HttpWebRequest;
postdata = BitmapToByte(image1); //convert image to byte. My suspisicion there is something wrong here
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.BeginGetRequestStream(HttpWebRequestButton2_RequestCallback, req);
}
}
private void HttpWebRequestButton2_RequestCallback(IAsyncResult result)
{
var req = result.AsyncState as HttpWebRequest;
using (var requestStream = req.EndGetRequestStream(result))
{
using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.Write(requestImageName+"="+this.postdata); //writing "picture=bytedata"
writer.Flush();
}
}
req.BeginGetResponse(HttpWebRequestButton_Callback, req);
}
private void HttpWebRequestButton_Callback(IAsyncResult result)
{
var req = result.AsyncState as HttpWebRequest;
var resp = req.EndGetResponse(result);
var strm = resp.GetResponseStream();
var reader = new StreamReader(strm);
this.Dispatcher.BeginInvoke(() => {
this.DownloadedText.Text = reader.ReadToEnd(); //the web page will print byte data that has been sent using httpwebrequest. i can see that byte data has benn sent sucessfuly.
this.DownloadedText.Visibility = System.Windows.Visibility.Visible;
});
}
private Stream ImageToStream(Image image1)
{
WriteableBitmap wb = new WriteableBitmap(400, 400);
wb.Render(image1, new TranslateTransform { X = 400, Y = 400 });
wb.Invalidate();
Stream myStream = new MemoryStream();
wb.SaveJpeg(myStream, 400, 400, 0, 70);
return myStream;
}
private string BitmapToByte(Image image) //i suspect there is something wrong here
{
Stream photoStream = ImageToStream(image);
BitmapImage bimg = new BitmapImage();
bimg.SetSource(photoStream); //photoStream is a stream containing data for a photo
byte[] bytearray = null;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap wbitmp = new WriteableBitmap(bimg);
wbitmp.SaveJpeg(ms, wbitmp.PixelWidth, wbitmp.PixelHeight, 0, 100);
ms.Seek(0, SeekOrigin.Begin);
bytearray = ms.GetBuffer();
}
string str = Convert.ToBase64String(bytearray);
return str;
}
and this is my code in php web page
if(isset($_REQUEST['picture'])) //check
{
$myFile = "picture.jpg";
$fh = fopen($myFile, 'wb') or die("can't open file");
$stringData = $_REQUEST['picture']."<br>";
$im = imagecreatefromstring($stringData);
if ($im) {
imagejpeg($im);
fwrite($fh, $im);
imagedestroy($im);
}
fclose($fh);
echo $stringData;
}
Please look at my question here: Photo upload with parameters to a PHP page
And my solution here: http://nediml.wordpress.com/2012/05/10/uploading-files-to-remote-server-with-multiple-parameters/

Flash AS3 PNGEncoder With Base64 and PHP Not Working

I am trying to utilize the PNGEncoder with the dynamicfash Base64 to send a Base64 String to PHP and save the PNG File but for some reason that i cannot figure out, the PNG file is never readable. It is there and has a size (contains data) but cannot be opened by anything so is not a valid png file. Here is my code...
var target:MovieClip = new MovieClip();
target.graphics.beginFill(0xff0000,5.0);
target.graphics.drawRect(0,0,100,100);
target.graphics.endFill();
var bdata:BitmapData = new BitmapData(100, 100);
bdata.draw(target);
var stream:ByteArray = PNGEncoder.encode(bdata);
var byteArrayAsString:String = Base64.encodeByteArray(stream);
var request:URLRequest = new URLRequest("pngsave.php");
request.method = URLRequestMethod.POST;
var variables:URLVariables = new URLVariables();
variables.fileName = "testing.png";
variables.image = byteArrayAsString;
request.data = variables;
navigateToURL(request, "_blank");
and the PHP Code...
<?php
header('Content-Type: image/png');
header("Content-Disposition: attachment; filename=".$_POST['fileName']);
echo base64_decode($_POST["image"]);
?>
Any ideas on what I am doing wrong here?
With FlashPlayer 10 (which has >95% adoption rate) you don't need to send the png data to a php page. Just use FileReference.save() instead.

Categories