I'm trying to send data from a VB.NET Application to a php application, i found this code:
Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(),contentType As String, method As String) As String
Dim req As WebRequest = WebRequest.Create(uri)
req.ContentType = contentType
req.Method = method
req.ContentLength = jsonDataBytes.Length
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Dim response = req.GetResponse().GetResponseStream()
Dim reader As New StreamReader(response)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()
Return res
End Function
Dim data = Encoding.UTF8.GetBytes(jsonSring)
Dim result_post = SendRequest(uri, data, "application/json", "POST")
at: source
But I can't get the posted data on php. It sends the headers, but the data no.
So, I need help to figure it out what is missing.
I also had same issue and got solution from comments only. As you are passing binary data then in php you need to read binary data as raw input
To get the Raw Post Data:
<?php $postdata = file_get_contents("php://input"); ?>
Related
I have Raspberry Pi RFID reader which is collecting simple ID numbers from tags nearby. Those are stored as a string variable. I want to continuously send this string value over to PHP script and display it on the web page and then store it in database. How do I pass this string value over using JSON in python?
Python Script:
import serial, os, httplib, json, urllib
#pyserial setup
tagID = tagID[:8] #true string tagID - 73203842
#JSON setup
headers = { "charset" : "utf-8", "Content-Type" : "application/json" }
conn = httplib.HTTPConnection("192.168.XX.XXX")
sample = { "ID" : tagID }
sJson = json.dumps(sample, ensure_ascii = 'False')
while True:
conn.request("POST", "/test.php", sJson, headers)
response = conn.getresponse()
print(response.read())
PHP File:
<?php
$data = json_decode($_POST['results']);
echo($data);
?>
I'm passing a large set of strings to my server from iOS (Swift) to a PHP file via POST. Unfortunately, if a user places an ampersand (&) in a field, the rest of the field is lost. I understand why (& signifies the next field in the message) but I'm not sure how to fix.
func UploadToSql(plan: LessonPlan, isNew: Bool, callBack: ((data: NSData!, response: NSURLResponse!, error: NSError!) -> Void)?) {
let url = NSURL(string: "https://myserver.com/receive.php")!
var request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
var bodyData = "Author=\(plan.author)&title=\(plan.title)&grade=\(plan.grade)&date=\"\(plan.date)\"&element1=\(plan.element1)&objective1=\(convertedFields[0])&element2=\(plan.element2)&objective2=\(convertedFields[1])&element3=\(plan.element3)&objective3=\(convertedFields[2])&coreProcess1=\(plan.coreProcess1)&coreStrand1=\(plan.coreStrand1)&coreStandard1=\(plan.coreStandard1)&coreProcess2=\(plan.coreProcess2)&coreStrand2=\(plan.coreStrand2)&coreStandard2=\(plan.coreStandard2)&coreProcess3=\(plan.coreProcess3)&coreStrand3=\(plan.coreStrand3)&coreStandard3=\(plan.coreStandard3)&media1=\(plan.media1)&media2=\(plan.media2)&media3=\(plan.media3)&media4=\(plan.media4)&media5=\(plan.media5)&media6=\(plan.media6)&repertoire1=\(convertedFields[3])&repertoire2=\(convertedFields[4])&repertoire3=\(convertedFields[5])&process=\(convertedFields[6])&assessment=\(convertedFields[7])&stateCat1=\(plan.stateCat1)&stateCat2=\(plan.stateCat2)&stateCat3=\(plan.stateCat3)&stateStand1=\(plan.stateStand1)&stateStand2=\(plan.stateStand2)&stateStand3=\(plan.stateStand3)&comment=\(plan.comment)&shared=\(sharedInt!)&authorName=\(plan.authorName)" + planID
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error=\(error)")
return
}
println("response = \(response)")
callBack?(data: data, response: response, error: error)
return
}
task.resume()
}
Typically for a webrequest like that it uses % followed by the ascii hex value. The hex value for & is 26, so it would be %26
google.com/#q=red%26white is example of a google search for red&white, which uses that replacement
Its called URL encoding or percent encoding and here is another question with an answer on how to do more broad URL encoding: stackoverflow.com/questions/24551816/swift-encode-url
Note that you would have to URL encode each element you were interpolating into the string, not the whole result string, as you want to keep your &'s that separate parameters.
This one is working for me. I am also using PHP/MySQL with NSURLSession.
func stringByAddingPercentEncodingForFormData(plusForSpace: Bool=false) -> String? {
let unreserved = "*-._"
let allowed = NSMutableCharacterSet.alphanumericCharacterSet()
allowed.addCharactersInString(unreserved)
if plusForSpace {
allowed.addCharactersInString(" ")
}
var encoded = stringByAddingPercentEncodingWithAllowedCharacters(allowed)
if plusForSpace {
encoded = encoded?.stringByReplacingOccurrencesOfString(" ",
withString: "+")
}
return encoded
}
Found above function from this link: http://useyourloaf.com/blog/how-to-percent-encode-a-url-string/.
I found a code for how to send a post to php but i can send only one variable.
Here is my code:
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim postData = "msg=" & TextBox2.Text
Dim request As WebRequest = WebRequest.Create("http://localhost/msg.php")
request.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
End Sub
If you read some documentation on how post works, you will find that each key/value pair has to be separated by a &.
Dim postData = "msg=" & TextBox2.Text & "&msg2=" & TestBox3.Text
You still need to make sure your value are properly encoded.
Dim postData = "msg=" & TextBox2.Text & "&msg2=" & TestBox3.Text
This statement will still be considered as a single array. (NOT two different values)
or you can say different values in single string.
I guess in order to send multiple values, we must have to use array with (key->value) combination.
where Key = msg and value will betextbox1.text and so on.
Note: I am limited to PHP <-> VBA. Please do not suggest anything that requires an Excel Addon, or any other language/method.
I have a function that connect to a specified URL, submits data, and then retrieves other data. This works great. I'm trying to write it so i can use it as a generic function I can use to connect to any file I need to connect to - each would return different data (one could be user data, one could be complex calculations etc).
When it retrieves the data from PHP, is there a way to dynamically set the variables based on what is received - even if i do not know what has been received.
I can make PHP return to VBA the string in any format, so I'm using the below as an example:
String that is received in vba:
myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday
If i were to parse this in PHP, I could do something similar to (not accurate, just written for example purposes);
$myData = "myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday"
$myArr = explode("&",$myData)
foreach($myArr as $key => $value){
${$key} = $value;
}
echo $someOtherValue; //Would output to the screen 'Hockey';
I would like to do something similar in VBA. The string I am receiving is from a PHP file, so I can format it any way (json etc etc), I just essentially want to be able to define the VARIABLES when outputting the string from PHP. Is this possible in VBA?.
The current state of the function I have that is working great for connections is as below:-
Function kick_connect(url As String, formdata)
'On Error GoTo connectError
Dim http
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "POST", url, False
http.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
http.send (formdata)
kick_connect = http.responseText
Exit Function
connectError:
kick_connect = False
End Function
Ultimately, I want to be able to do something like
sub mySub
myData = "getId=" & Range("A1").Value
myValue = kick_connect("http://path-to-my-php-file.php",myData)
if myValue = False then
'Handle connection error here
exit sub
end if
'do something snazzy here to split "myValue" string (eg "myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday") into own variables
msgbox(myValue1) 'Should output "Dave"
end sub
Obviously I could put the values into an array, and reference that, however I specifically want to know if this exact thing is possible, to allow for flexibility with the scripts that already exist.
I hope this makes sense, and am really grateful for any replies i get.
Thank you.
You can use a Collection:
Dim Tmp As String
Dim s As String
Dim i As Integer
Dim colVariabili As New Collection
Tmp = "myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday"
Dim FieldStr() As String
Dim FieldSplitStr() As String
FieldStr = Split(Tmp, "&")
For Each xx In FieldStr
FieldSplitStr = Split(xx, "=")
colVariabili.Add FieldSplitStr(1), FieldSplitStr(0)
Next
Debug.Print colVariabili("myValue1")
Debug.Print colVariabili("someOtherValue")
Debug.Print colVariabili("HockeyDate")
It's ok if you don't have the correct sequence of var...
I am not sure if this can help you, but as far as I understand your question you want to be able to create the variables dynamically based on the query string parameters. If so then here is example how to add this variables dynamically. Code needs standard module with a name 'QueryStringVariables'. In this module the query string will be parsed and each query string parameter will be added as get-property. If you wish to be able to change the value as well then you will need to add let-property as well.
Add reference to Microsoft Visual Basic For Applications Extensibility
Option Explicit
Private Const SourceQueryString As String = "myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday"
Sub Test()
Dim queryStringVariablesComponent As VBIDE.vbComponent
Dim queryStringVariablesModule As VBIDE.CodeModule
Dim codeText As String
Dim lineNum As Long: lineNum = 1
Dim lineCount As Long
Set queryStringVariablesComponent = ThisWorkbook.VBProject.VBComponents("QueryStringVariables")
Set queryStringVariablesModule = queryStringVariablesComponent.CodeModule
queryStringVariablesModule.DeleteLines 1, queryStringVariablesModule.CountOfLines
Dim parts
parts = Split(SourceQueryString, "&")
Dim part, variableName, variableValue
For Each part In parts
variableName = Split(part, "=")(0)
variableValue = Split(part, "=")(1)
codeText = "Public Property Get " & variableName & "() As String"
queryStringVariablesModule.InsertLines lineNum, codeText
lineNum = lineNum + 1
codeText = variableName & " = """ & variableValue & ""
queryStringVariablesModule.InsertLines lineNum, codeText
lineNum = lineNum + 1
codeText = "End Property"
queryStringVariablesModule.InsertLines lineNum, codeText
lineNum = lineNum + 1
Next
DisplayIt
End Sub
Sub DisplayIt()
MsgBox myValue1 'Should output "Dave"
End Sub
I am writing a php program to write a binary file (may be video or image files). I would like to make it as a web service and call it from another application like c#, mac etc.
My code is give below,
<?php
$fileChunk = $_POST["filechunk"];
$vodFolder = 'D:\\HYSA SVN\\Trunk\\workproducts\\source\\hysa_he\\web\\entertainment\\';
$vodFile = $vodFolder . "abcd.mov";
$fh = fopen($vodFile, 'ab');
flock ($fh, LOCK_EX);
$varsize = fwrite($fh, $fileChunk);
fclose($fh);
?>
But when I called the php web service from a c# code, the abcd.mov is creating in the location, but its size is only one kb. I suspects that, the writing in halted when a character ‘&’ found in the binary file. I read the php documentation and found that, fopen with binary mode ‘b’ will solve this issue? But it is not working. Can somebody help me ?
This is my c# code.
BinaryReader b = new BinaryReader(File.Open("d:\\image38kb.jpg", FileMode.Open));
int pos = 0;
int length = (int)b.BaseStream.Length;
byte[] bt = b.ReadBytes(length);
char[] ch = b.ReadChars(length);
HttpWebRequest request = null;
Uri uri = new Uri("http://d0327/streamtest.php");
request = (HttpWebRequest)WebRequest.Create(uri);
NetworkCredential obj = new NetworkCredential("shihab.kb",
"India456*", "tvm");
request.Proxy.Credentials = obj;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bt.Length;
using (Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes("filechunk=");
byte[] rv = new byte[bytes.Length + bt.Length];
System.Buffer.BlockCopy(bytes, 0, rv, 0, bytes.Length);
System.Buffer.BlockCopy(bt, 0, rv, bytes.Length, bt.Length);
writeStream.Write(rv, 0, bt.Length);
}
string result = string.Empty;
using (
HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
Well the problem is not in the fwrite part, that works fine.
However, POST requests in HTTP look like this:
POST /somepage.php HTTP/1.1
Content-Length: 34
variable1=blah&var2=something else
As you can see, variables are divided by ampersands (&) (as well as equal signs (=) for the key - value mapping)... So, even when using POST requests, ampersands are not safe characters.
To solve this, you could try another transfer method, for example, TCP/IP socket connection, or simply escape the ampersands with, say '\x26' (the ASCII value of ampersand) and escape all the backslashes (\) with '\x5C'... You'd have to edit the PHP code to parse these values.