In this article, Mitchell shows us how to implement our custom SARP protocol that we created yesterday. He uses PHP and its various socket functions to send SARP commands to our SARP server to both retrieve articles and add new articles to the servers Access database.
Building A Document Request Protocol Part 2/2 - Logging in (Page 3 of 6 )
Our SARP protocol understands the "LOGIN" command, with which we can specify a username and password to request a login. We must send a string of text to our SARP server in this format:
LOGIN [Username] [Password]
The fputs function allows us to send some data to our SARP server. Its signature looks like this:
int fputs (int fp, string string [, int length])
As you can see, fputs accepts a reference to a file stream, a string variable (which is the actual data that will be sent to the remote computer, as well as an optional length parameter, which can be used to specify the length of the string variable being sent.
Notice how I said that fputs accepts a reference to a file stream? The good thing about working with streams in PHP is that there is one set of functions that can be used to manipulate streams, no matter what type of object they're pointing to: sockets, files, or even communication ports and printers. This makes it extremely easy to debug your code or redirect output to another stream, for example.
We use the fputs function to login to our SARP server like this:
fputs($sarpHandle, "LOGIN $xUser $xPass");
Once our SARP server sees the LOGIN command, it will return a status number and message, indicating whether or not the login succeeded or failed. The values for the login are hard coded into our VB app, and for the login to be successful, the username must be "XUSER", and the password must be "XPASS". Here's the VB code that validates the login:
Private Function DoLogin(ByVal strUser As String, ByVal strPass As String)
If UCase(strUser) = "XUSER" And UCase(strPass) = "XPASS" Then
DoLogin = "102 Login OK"
blnLoggedIn = True
DoLogin = "103 Login Failed"
blnLoggedIn = False
As you can see, if the login is successful, "102 Login OK" is returned. If not, "103 Login Failed" is returned. We use PHP's fgets function to retrieve data from the remote computer, like this:
$sarpData = fgets($sarpHandle, 1024);
In our example above, fgets returns a string of up to 1023 bytes from the socket connection referenced by the $sarpHandle pointer. When we pass "LOGIN XUSER XPASS" to our SARP server, the $sarpData variable contains "102 Login OK".
Using PHP's ereg function, we can create a regular expression to make sure that the response from the remote computer contains "102" at the beginning, indicating that we have logged in successfully: