Posting GZipStream to PHP failing to deflate - php

I am trying to post JSON using GZipStream to PHP but am not sure how to deflate it on the PHP side. Here is the function to compress:
public static string Compress( string text) {
var buffer = Encoding.UTF8.GetBytes(text);
var memoryStream = new MemoryStream();
using (var stream = new GZipStream(memoryStream, CompressionMode.Compress, true)) {
stream.Write(buffer, 0, buffer.Length);
}
memoryStream.Position = 0;
var compressed = new byte[memoryStream.Length];
memoryStream.Read(compressed, 0, compressed.Length);
var gZipBuffer = new byte[compressed.Length + 4];
Buffer.BlockCopy(compressed, 0, gZipBuffer, 4, compressed.Length);
Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gZipBuffer, 0, 4);
return Convert.ToBase64String(gZipBuffer);
}
It is being called like this:
request.Headers.Add("Content-Encoding", "gzip");
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
postData = Compress(JsonConvert.SerializeObject(incomingData));
byteArray = Encoding.UTF8.GetBytes(postData);
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
On the PHP side I am doing this to receive it:
<?PHP
file_put_contents('test.txt', file_get_contents('php://input'));
file_put_contents('test2.txt', gzuncompress('php://input'));
?>
In my apache error log I get this:
PHP Warning: gzdecode(): data error in /var/www/html/gzip.php on line 3
and in test.txt I get this:
0QAAAB+LCAAAAAAABAAdjsEKgzAQRH9lycWLlfbquVLoRWntqelhiYsGZJNuorUU/70htzcPZhj102rAiFrVz4SNiJOWOxwpGa06F+I1OO7dnWQlgQM0myEfrePEvXxB6L1QiNWF4o2CdxxStdTqTBHtHPLMKZs8nvODafNkIg1gJhRMJEBs3MKJkv1MdibwKMHyCCvOC9XQVtBhnKAoSpgtExxL8C7YfOZYabW/dvUHutMCTtEAAAA=
I have also tried gzdecode, gzinflate, what should I do next to get my JSON back so I can process it with PHP?
UPDATE:
I tried doing what Sammitch suggested, but still getting errors. Using this (https://gist.github.com/magnetikonline/650e30e485c0f91f2f40) to dump all the request info provides the following:
POST /gzip.php HTTP/1.1
HTTP headers:
Authorization: Bearer xxxx
Host: mysite.com
Expect: 100-continue
Request body:
0QAAAB+LCAAAAAAABAAdjsEKgzAQRH9lyaUXK/bqWSn0UmntqelhiYsGZJNuorUU/70htzcPZhj102rAiFrVz4StiJMrdzhSMlp1LsRLcNy7O8lKAkdoN0M+WseJe/mC0HuhEMszxRsF7zikaqFVQxHtHPLMKZs8nvODafNkIg1gJhRMJEBs3MKJkv1MdibwKMHyCCvOC9XQlNBhnOBwKGC2TFAV4F2w+UxVarW/dvUHpEHFyNEAAAA=
I tried it both with and without the base64.

Related

How to get a JSON in a POST request in PHP

The issue is, that I am sending a JSON file in a POST request but i don't know how to get the data from the request itself
Here is the python script that sends the POST request:
import json
import httplib
filepath = 'example.txt'
with open(filepath) as fp:
line = fp.readline()
line2 = fp.readline(9)
jsonbaloo = {}
jsonbaloo["name"] = line
jsonbaloo["score"]= line2
result = json.dumps(jsonbaloo)
def post_dict():
headers = {"Content-type": "application/json", "Accept": "text/plain"}
conn = httplib.HTTPConnection('altrevista.org')
conn.request("POST", "/", result, headers)
post_dict()
I want to get the JSON data server side, so I can put it on an SQL database, but I can't program in PHP.
PHP SCRIPT:
<?php
function detectRequestBody() {
$rawInput = fopen('php://input', 'r');
$tempStream = fopen('php://temp', 'r+');
stream_copy_to_stream($rawInput, $tempStream);
rewind($tempStream);
return $tempStream;
}
?>
conn.read() to get the response back
Since you're writing to a file, you can read from the file using PHP with fopen() or file_get_contents().
Using fopen():
$fileHandle = fopen("path/to/example.txt", "r");
Using file_get_contents():
$fileString = file_get_contents("path/to/example.txt");
You should receive the data using file_get_contents (php://input stream) and convert it to an array using json_decode.
// Retrieve the Post JSON data
$input = file_get_contents('php://input');
// Convert to json to array
$array = json_decode($input, true);
// View the content of the array
print_r($array);

vb.net receiving response from a php script

My application (written in vb.net) send data to a php script hosted on one of the free webhosting servers. The php script evaluates the data, and responds accordingly. The response from the server looks something like this:
Valid
<!-- Hosting3322 Analytics Code -->
<script type="text/javascript" src="theurlforthewebsite/count.php"></script>
<!-- End of Analytics Code -->
'Valid' is from my php script. Rest of is a little script by the server that they hide in every page.
Here is the php script:
<?php
$d = $_POST['mac'];
if($d=='45bgd0434')
echo "Valid";
else
echo "Invalid";
?>
Here is my vb.net code:
' Create a request using a URL that can receive a post.
Dim request As WebRequest = WebRequest.Create("http://sitename.com/verify.php")
' Set the Method property of the request to POST.
request.Method = "POST"
' Create POST data and convert it to a byte array.
Dim postData As String = "mac=45bgd0434"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
' Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded"
' Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length
' Get the request stream.
Dim dataStream As Stream = request.GetRequestStream()
' Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length)
' Close the Stream object.
dataStream.Close()
' Get the response.
Dim response As WebResponse = request.GetResponse()
' Get the stream containing content returned by the server.
dataStream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
' Clean up the streams.
reader.Close()
dataStream.Close()
response.Close()
MessageBox.Show(responseFromServer)
I would just like to have only the output and not that extra code. Is there any way I can use an alternative method to print in PHP, or probably another method with which I can talk to the server?
I have tried other free servers on the internet, but they all seem to put in some code. Would really appreciate your help.

android: get string with correct encoding from web service

I am trying get string result from PHP webservice in my android application, I used ksaop2 library and this is my code :
env = new SoapSerializationEnvelope(SoapEnvelope.VER11);
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
request = new SoapObject("customWebService","addProductToCart");
request.addProperty("sessionID", sessionId);
request.addProperty("cartID", cartID);
request.addProperty("productID", productID);
request.addProperty("qty", qty);
request.addProperty("sku", productSKU);
env.setOutputSoapObject(request);
androidHttpTransport = new HttpTransportSE(
"http://mysiteeee.com/WebServiceSOAP/server.php?wsdl/",
60000);
androidHttpTransport.debug = true;
androidHttpTransport.call("", env);
result = env.getResponse();
It`s returned this:
???·???§?? ?¯?²?????? (???§??) ?§???²?§???? ???­?µ???? ?±?§ ???´?®?µ ?©?????¯.
I tested it on Chrome and Firefox with UTF-8 encoding and shows result correctly on browser.
How can I get result from web service with correct encoding and show it on android?
Try getting response this way :
androidHttpTransport.call(SOAP_ACTION, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject)envelope.bodyIn;
String Test1 = result.getProperty(0).toString();
Edit : Try setting Xml header Tag for request :
androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

imagecreatefromstring is causing 500 internal server error

I have bitmao instance i convert this instance into base64string and send it to server over php function. Now i am decoding this string and calling imagecreatefromstring but this function is giving 500 internal server error. I want this image to be store into file.
My .net function is as follows:
Bitmap icon = new Bitmap("C:\\Users\\HP\\Desktop\\mun.ico");
System.IO.MemoryStream stream = new System.IO.MemoryStream();
icon.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] imageBytes = stream.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
HttpWebRequest m_ObjRequest; //Request which needed to be sent to server
HttpWebResponse m_ObjResponse; // Response which is sent back from the server to the client
StreamReader reader = null; // making a stream reader to read the web pageand initialize it to null
string m_Url = "http://192.168.1.30/muneem/erp/uploadIcon.php"+ "?bitmap=" + base64String; // the url of that web page
string m_Response = "";
m_ObjRequest = (HttpWebRequest)WebRequest.Create(m_Url); // creating the url and setting the values
m_ObjRequest.Method = "GET";
m_ObjRequest.ContentType = "application/json; charset=utf-8";
//m_ObjRequest.ContentLength = 500;
m_ObjRequest.KeepAlive = false;
m_ObjResponse = (HttpWebResponse)m_ObjRequest.GetResponse(); // getting response from the server
using (reader = new StreamReader(m_ObjResponse.GetResponseStream())) // using stream reader to read the web page
{
m_Response = reader.ReadToEnd();
reader.Close(); // Close the StreamReader
}
m_ObjResponse.Close();
m_ObjRequest = null;
m_ObjResponse = null;
My php code to handle this encoded bitmap string is as follows:
$bitmap=$_GET['bitmap'];
$data = base64_decode($bitmap);
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
encoded bitmap string is as follows:
$bitmap="Qk02BAAAAAAAADYAAAAoAAAAEAAAABAAAAABACAAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPasAP/2rAD/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA9qwA//asAP9L/9v/S//b//asAP/2rAD/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA9qwA/0v/2/9L/9v/S//b/0v/2/9L/9v/S//b//asAP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPasAP9L/9v/S//b/0v/2/9L/9v/S//b/0v/2//2rAD/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPasAP9L/9v/S//b/0v/2/9L/9v/S//b/0v/2/9L/9v/S//b//asAP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2rAD/S//b/0v/2/9L/9v/S//b/0v/2/9L/9v/S//b/0v/2//2rAD/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPasAP9L/9v/S//b/0v/2/9L/9v/S//b/0v/2//2rAD/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2rAD/S//b/0v/2/9L/9v/S//b/0v/2/9L/9v/9qwA/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPasAP/2rAD/S//b/0v/2//2rAD/9qwA/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPasAP/2rAD/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="
why i am getting this error on imagecreate from string?
BMP format is not supported by imagecreatefromstring. Allowed formats are: JPEG, PNG, GIF, WBMP, and GD2.

send both string and buffer using httplib with python to the server

How can I POST parameters with a file object to a URL using httplib in python web services.
Am using the following scripts:
import httplib
import urllib
params = urllib.urlencode({"#str1":"string1", "#str2":"string2", "#file":"/local/path/to/file/in/client/machine", "#action":"action.php" })
headers = {"Content-type":"application/pdf , text/*" }
conn = httplib.HTTPConnection("192.168.2.17")
conn.request("POST", "/SomeName/action.php", params, headers)
response = conn.getresponse()
print response.status, response.reason
data = response.read()
data
conn.close()
And I have the following output:
200
OK
<html>.....some html code </html>
I wrote some php code for save those string and the file in DB
My problem is that, Am only getting the file path as a sting but not my file.
May be I have to send the file object like,
file_obj = open("filename.txt","r")
conn.request("POST", "/SomeName/action.php", file_obj, headers)
But I want to send both strings and file. Any suggestions to solve this?
EDIT
I change my code as follows:
When i send a pdf file, by directly using httplib, to my server the file saves as BIN file.
def document_management_service(self,str_loc_file_path,*args):
locfile = open(str_loc_file_path,'rb').read()
host = "some.hostname.com"
selector = "/api/?task=create"
fields = [('docName','INVOICE'),('docNumber','DOC/3'),('cusName','name'),('cusNumber','C124'),('category','INVOICE'),('data','TIJO MRS,SOME/DATA/CONTENT,Blahblah,2584.00,blahblah'),('action','create')]
files = [('strfile','File.pdf',locfile)]
response = self.post_multipart(host, selector, fields, files)
print response
pass
def post_multipart(self,host, selector, fields, files):
content_type, body = self.encode_multipart_formdata(fields, files)
h = httplib.HTTP(host)
h.set_debuglevel(1)
h.putrequest('POST', selector)
h.putheader('content-type', content_type)
h.putheader('content-length', str(len(body)))
h.putheader('Host', host)
h.endheaders()
h.send(body)
errcode, errmsg, headers= h.getreply()
return h.file.read()
def encode_multipart_formdata(self, fields, files):
LIMIT = '----------lImIt_of_THE_fIle_eW_$'
CRLF = '\r\n'
L = []
for (key, value) in fields:
L.append('--' + LIMIT)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
for (key, filename, value) in files:
L.append('--' + LIMIT)
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
L.append('Content-Type: %s' % self.get_content_type(filename))
L.append('')
L.append(value)
L.append('--' + LIMIT + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % LIMIT
return content_type, body
def get_content_type(self, filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
I have debug the request which shows as:
[('content-length', '4191'), ('accept-ranges', 'bytes'), ('server', 'Apache/2.2.12 (Ubuntu)'), ('last-modified', 'Tue, 23 Oct 2012 04:46:36 GMT'), ('etag', 'W/"567dd-105f-4ccb2a7a9a500"'), ('date', 'Tue, 23 Oct 2012 04:46:36 GMT'), ('content-type', 'application/pdf')]
multipart/form-data; boundary=----------lImIt_of_THE_fIle_eW_$
And I didn't try requests,Coz I would like to solve this with httplib(without any external lib)
To post parameters and a file in a body you could use multipart/form-data content type:
#!/usr/bin/env python
import requests # $ pip install requests
file = 'file content as a file object or string'
r = requests.post('http://example.com/SomeName/action.php',
files={'file': ('filename.txt', file)},
data={'str1': 'string1', 'str2': 'string2'})
print(r.text) # response
requests.post sends to the server something like-this:
POST /SomeName/action.php HTTP/1.1
Host: example.com
Content-Length: 449
Content-Type: multipart/form-data; boundary=f27f8ef67cac403aaaf433f83742bd64
Accept-Encoding: identity, deflate, compress, gzip
Accept: */*
--f27f8ef67cac403aaaf433f83742bd64
Content-Disposition: form-data; name="str2"
Content-Type: text/plain
string2
--f27f8ef67cac403aaaf433f83742bd64
Content-Disposition: form-data; name="str1"
Content-Type: text/plain
string1
--f27f8ef67cac403aaaf433f83742bd64
Content-Disposition: form-data; name="file"; filename="filename.txt"
Content-Type: text/plain
file content as a file object or string
--f27f8ef67cac403aaaf433f83742bd64--
To reproduce it with httplib see POST form-data with Python example.
A simpler solution if your parameters do not contain much data is to pass them in the url query part and leave the body to contain only the file:
#!/usr/bin/env python
import urllib
import requests # $ pip install requests
params = {'str1': 'string1', 'str2': 'string2', 'filename': 'filename.txt'}
file = 'file content as a file object or string, etc'
url = 'http://example.com/SomeName/action.php?' + urllib.urlencode(params)
r = requests.post(url, data=file, headers={'Content-Type': 'text/plain'})
print(r.text) # response
It corresponds to the following HTTP request:
POST /SomeName/action.php?str2=string2&str1=string1&filename=filename.txt HTTP/1.1
Host: example.com
Content-Length: 39
Content-Type: text/plain
Accept-Encoding: identity, deflate, compress, gzip
Accept: */*
file content as a file object or string
It should be easier to translate to httplib if you need it.
The following code can also solve the problem with transfering file with other meta data using httplib (with out any external libraries):
def document_management_service_success(self,str_loc_file_path,*args):
locfile = open(str_loc_file_path,'rb').read()
str_loc_file = locfile.split('#end_pymotw_header')
initial_data = str_loc_file[0]
encoded_data = ''.join("{0:08b}".format(ord(c)) for c in initial_data)
params = urllib.urlencode({'docName':'INVOICE', 'docNumber':'RF/2', 'cusName':'Tijo john', 'cusNumber':'C124', 'category':'INVOICE', 'data':encoded_data})
headers = {"Accept": "Text/*","Content-Disposition":"form-data" ,"Content-Type": "application/x-www-form-urlencoded, application/pdf, form-data"}
conn = httplib.HTTPConnection("efiling.nucoreindia.com")
conn.connect()
conn.set_debuglevel(1)
conn.request("POST", "/api/?task=create", params, headers)
response = conn.getresponse()
print "Server Response status is"+str(response.status)+"and Reason is,"+str(response.reason)
print response.getheaders()
print response.read()
pass

Categories