I need a PHP Server to interact with my wireless sensors. But I also need that server to be controlled by a Visual Basic Application.
Some of the features I need in the Visual Basic Application:
Start/Stop Server
Server Configuration
Access files on the server directory.
The PHP file (server application) is simply to accept data from the wireless sensor module and store in a flat database file (CSV, XML). After this data has been written Visual Basic must access the flat database file to perform analysis.
Any suggestions on what server to use and what particular methods might provide the easiest solution?
Well, what you want is broad and yet, there is not enough information about your PHP part.
But I can help you with VB.NET. Here is a Class (And a Sub and an Event) that can really help.
Some Examples first
Simply loads a HTML code:
Dim Page As New WEBhtml("http://www.example.com/index.php?get=something")
While Page.IsReady = False
End While
If IsNothing(Page.Exception) Then
MsgBox(Page.GetHtml)
Else
MsgBox(Page.Exception.Message)
End If
Sends POST to destination (just the Dim line):
Dim Page As New WEBhtml("http://www.example.com/index.php?get=something", {"a=alpha", "b=beta", "c=I Don't Know :D !"})
Use Handling:
Private Sub form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Page As New WEBhtml("http://www.e.com/i.php")
End Sub
Private Sub html_done(ByRef sender As WEBhtml) Handles Me.WebHtml_Done
MsgBox("Timetook: " & sender.TimeTook / 1000 & "s")
MsgBox("Url: " & sender.Url)
If IsNothing(sender.Exception) Then
MsgBox("Bandwidth: " & sender.Bytes / 1024 & "kb")
MsgBox("HTML: " & sender.GetHtml)
Else
MsgBox("Error: " & sender.Exception.Message)
End If
End Sub
See? very easy.
Now to Start
Follow these two steps
First: Add System.Web Reference
Go to Project > [Project name] Properties > Reference
After that press the "Add..." button, and check 'System.Web'
Then press Ok. also check it in 'Imported namespaces'
Second: Copy this block before the 'End Class'
Public Shared Event WebHtml_Done(ByRef sender As WEBhtml)
Friend Shared Sub RaiseDone(ByRef wh As WEBhtml)
RaiseEvent WebHtml_Done(wh)
End Sub
Public Class WEBhtml
Private thrd As Threading.Thread
Private Err As Exception
Private BytesUsed As ULong = 0
Private Time As UInteger = 0
Private Html As String = ""
Private _Url As String
Private tmr As New Timer
Private Sub initialize()
tmr.Interval = 50
AddHandler tmr.Tick, AddressOf Tick
tmr.Enabled = True
tmr.Start()
End Sub
Public Sub New(ByVal Url As String)
thrd = New Threading.Thread(Sub() WEB_POST(Url))
initialize()
thrd.Start()
End Sub
Public Sub New(ByVal Url As String, ByVal PostData As String())
thrd = New Threading.Thread(Sub() WEB_POST(Url, PostData))
initialize()
thrd.Start()
End Sub
Private Sub Tick(sender As Object, e As EventArgs)
If thrd.IsAlive = False Then
tmr.Enabled = False
RaiseDone(Me)
End If
End Sub
Private Sub WEB_POST(ByVal url As String, Optional ByVal values() As String = Nothing)
_Url = url
Dim data As String = ""
Dim a, b As Integer
b = My.Computer.Clock.TickCount
Try
For i = 0 To values.GetLength(0) - 1
a = values(i).IndexOf("=")
If a >= 0 Then
data += System.Web.HttpUtility.UrlEncode(Mid(values(i), 1, a)) & "=" & System.Web.HttpUtility.UrlEncode(Mid(values(i), a + 2))
If i < values.GetLength(0) - 1 Then data += "&"
End If
Next
Catch
data = ""
End Try
Try
Dim request As System.Net.WebRequest = System.Net.WebRequest.Create(url)
request.Method = "POST"
Dim postdata As String = data
Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes(postdata)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
request.Timeout = 100000
Dim dataStream As IO.Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As Net.WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As New IO.StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
BytesUsed += responseFromServer.Length + byteArray.Length
Time = My.Computer.Clock.TickCount - b
Html = (responseFromServer)
Catch ex As Exception
Err = ex
Time = My.Computer.Clock.TickCount - b
Html = ""
End Try
End Sub
Public ReadOnly Property Exception() As Exception
Get
Return Err
End Get
End Property
Public ReadOnly Property TimeTook() As UInteger
Get
Return Time
End Get
End Property
Public ReadOnly Property Bytes() As ULong
Get
Return BytesUsed
End Get
End Property
Public ReadOnly Property GetHtml() As String
Get
Return Html
End Get
End Property
Public ReadOnly Property IsReady() As Boolean
Get
Return Not thrd.IsAlive
End Get
End Property
Public ReadOnly Property Url() As String
Get
Return _Url
End Get
End Property
End Class
I believe this works properly.
Hope It Helps.
Related
I have coded a basic PHP script that collects the data from a few HTML forms and writes it to a text document, and then configured Access to link this text document to a table and import automatically. This all works fine but the problem is that Access seems to be always using this file meaning that my script can't write to it. How can I get Access to check the document every so often, look at what is there and import it without any duplicate data?
two ways:
Dim strFilename As String: strFilename = "C:\temp\yourfile.txt"
Dim strTextLine As String
Dim iFile As Integer: iFile = FreeFile
Open strFilename For Input As #iFile
Do Until EOF(1)
Line Input #1, strTextLine
Loop
Close #iFile
or you can use below code:
Dim intFile As Integer
Dim strFile As String
Dim strIn as String
Dim strOut As String
strOut = vbNullString
intFile = FreeFile()
strFile = "C:\Folder\MyData.txt"
Open strFile For Input As #intFile
Do While Not EOF(intFile)
Line Input #intFile, sIn
If Left(strIn, 7) = "KeyWord" Then
strOut = Mid(strIn, 8)
booFound = True
Exit Do
Loop
Close #intFile
If Len(strOut) > 0 Then
MsgBox "Your Data is " & strOut
Else
MsgBox "Keyword Not Found"
End If
more info . . .More Info . . .
Private Sub txtRFID_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtRFID.TextChanged
Try
Dim search As New MySqlCommand("SELECT * FROM `users` WHERE `rfid`=#rfid", connection)
search.Parameters.Add("#rfid", MySqlDbType.VarChar).Value = txtRFID.Text
Dim adapter As New MySqlDataAdapter(search)
Dim table As New DataTable()
Dim imgByte() As Byte
adapter.Fill(table)
lblMName.Text = table(0)(5)
lblFName.Text = table(0)(4)
lblLName.Text = table(0)(3)
lblCourse.Text = table(0)(10)
lblYear.Text = table(0)(11)
imgByte = table(0)(12)
Dim ms As New MemoryStream(imgByte)
PictureBox1.Image = Image.FromStream(ms)
adapter.Dispose()
Catch ex As Exception
MessageBox.Show("Card not registered in database !")
txtRFID.Text = ""
returnStr = ""
End Try
End Sub
Here is my code for searching record , i can search it when i copy paste the rfid code in the "txtRFID.text". But when i swipe an RFID card it does nothing and return error wherein the serial monitor return the exact value to the "txtRFID.text" textbox.
Heres the code of my serial monitor read :
Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim id As String = SerialPort1.ReadLine()
returnStr &= id
txtRFID.Text = returnStr
End Sub
and the declaration for returnStr
Public Class Form1
Dim returnStr As String
Dim connection As New MySqlConnection("datasource=localhost;port=3306;username=root;password=;database=xxxxx") ....
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
How can I fill in a FileSelection in a PHP Form through a Visual Basic 6 Webbrowser control?
I want to send a file to upload on a site and I must change File in the page as manualy,
is there any way to solve that?
I created a simple sample project which seems to do what you want.
'1 form with :
' 1 webbrowser control : name=WebBrowser1
' 1 command button : name=Command1
Option Explicit
Private Sub Command1_Click()
WebBrowser1.Navigate "www.dailygammon.com/bg/login"
End Sub
Private Sub Form_Resize()
Dim sngWidth As Single, sngHeight As Single
Dim sngCmdHeight As Single
sngCmdHeight = 315
sngWidth = ScaleWidth
sngHeight = ScaleHeight - sngCmdHeight
WebBrowser1.Move 0, 0, sngWidth, sngHeight
Command1.Move 0, sngHeight, sngWidth, sngCmdHeight
End Sub
Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)
Dim strName As String
Dim retVal
strName = "your name"
retVal = WebBrowser1.Document.GetElementsByName("login")
retVal.Value = strName
End Sub
I never played with this before, so there are probably quite some things that could be improved. For example, the variable type of retVal which is Variant now.