VB.NET + MySQL + PHP Registration And Login

Posts 1–15 of 32 · Page 1 of 3
VB.NET + MySQL + PHP Registration And Login
Hi,

In this tutorial we will be creating a registration and login system using a combination of VB.NET, MySQL and PHP. You will need administrative access to cPanel (you have one, if you own a domain and hosting). You'll also need Visual Basic.NET of course.

So, let's start:

First, open cpanel (http://cpanel.yourdomainname.com) and login:



This will open the control panel for you. Scroll down until you find the Databases section. In this section, click MySQL Databases as shown below:



This will open a new page where you can manage your databases and its users. Now, under the Create New Database heading, write down the name of the database you want to create and click Create Database.



If the Database creation is successful, you will see a notification like the following:



Click Go Back so we can add a user to our Database. Now scroll down the page until you see the heading named Add New User. Here, choose a username (I've chosen admin). Create a secure password and press Create User button to create the user:



If the user was added successfully, you'll see a notice similar to the following:



Click Go Back to return to the previous page. Now we need to add the user to our database. Scroll down until you see the Add User To Database heading. Choose the user we just created and our database from the drop down boxes as shown:



Click Add to add the user to Database. You will be taken to a page where you will manage the user privilege. Click on All Privileges to give full permission to the user. Next, click Make Changes to apply the permissions.



If successful, you will see the following notification:



We've successfully created our database. Now we need to write some PHP to create the table for our database. This table will store the usernames and serials.

Open Notepad++ or any editor you are comfortable with. Write the following code in it:

Code:
<?php
$connect = mysql_connect("localhost","crorib_admin","userpassword");//Replace the crorib_admin with your username and userpassword with the password you are using for that user. This line connects to the MySQL engine.
if($connect)
{
	$TableQuery="CREATE TABLE users (Username varchar(255), Serial varchar(500))"; //This line defines a MySQL query which creates a table named "users" that has the two columns. 1: Username (which can store maximum of 255 characters). 2: Serial (which can store maximum of 500 characters). 
	$select = mysql_select_db("crorib_serials",$connect); //Replace crorib_serials with the name of the database you created. This line selects the database in which we want to add our new table.
	if($select)
	{
		if(mysql_query($TableQuery)) //This line tries to execute the query we created above. If the table is created successfully, it returns true. Otherwise, it returns false.
		{
			die ('Table created successfully. You can delete setup.php now.'); //Display a success message and exit.
		}
		else
		{
			die ("Failed to create the table. " . mysql_error()); //Display failure message and exit.
		}
	}
	else
	{
		die("Unable to select database." . mysql_error()); //Unable to select the database. Display failure message and exit.
	}
}
else
{
	echo 'Failed to connect.' . mysql_error(); //Failed to connect. Display failure message and exit.
}
?>
Save this file as "setup.php" (notice the .php extension).

Now, go back to main page of the control panel and find "File Manager".



Click the File Manager. You will see a dialog asking for directory to open. We need to go to parent directory of the site so we can create a folder there. So, choose your domain name from the list. e.g: mysite.com



Press Go. This will open a new tab / window and will show you a list of your site's root files and folders. Click New Folder from the toolbar that is displayed on top of the page as shown below:



After clicking, you will be presented with a dialog where you will have to enter the name of the folder that you want to create. Enter a name for the folder and press Create New Folder.



This will create a new folder. Find your new folder in the list and open it by double clicking it:



The folder will be empty of course. We now need to put our setup.php (an a few other which we will write later) in this folder. From the toolbar on the top of the page, click Upload button. This will open a new tab.



On the upload page, click Choose File and select the setup.php file that we created earlier. This will upload the file.



On the bottom of the page, you will see a success message:



Next, open a new tab in your browser and open the file we just uploaded (setup.php). If you followed my instructions exactly as they are written, then the path would be something like:

http://mydomainname/authentication/setup.php

If navigated successfully and the table is created successfully, you will see the following output:



Now, if you want, you can delete the setup.php (or if you want to keep it for later use, at least rename it).

Moving on, we need to quickly write two php files that will store and load the username and serials from the database. Again, open your favourite editor and write the following code in it:

Code:
<?php
if($_POST) //Make sure it is a post request.
{
	if(isset($_POST["username"]) && isset($_POST["serial"])) //Make sure username and serial are provided.
	{
		$connect = mysql_pconnect("localhost","crorib_admin","yourusername"); //Connect to the database. //Replace the crorib_admin with your username and userpassword with the password you are using for that user. This line connects to the MySQL engine.
		if($connect) //If successfully connected.
		{
			$select = mysql_select_db("crorib_serials",$connect); //Select the database you created. Replace crorib_serials with your database name.
			if($select)
			{
				$user = mysql_escape_string($_POST["username"]); //Variable user that stores our username that was passed as a post request.
				$serial = mysql_escape_string($_POST["serial"]); //Variable serial that stores our serial name for the user that was passed as a post request.
				$NewUser = "INSERT INTO users VALUES ('$user','$serial')"; //MySQL query that adds the username and serial to the table.
				if(mysql_query($NewUser)) //If added successfully
				{
					die("User added successfully.");  //Display success message and exit.
				}
				else
				{
					die("Unable to add user to the database." . mysql_error());  //Unable to add the user. Display failure message and exit.
				}
			}
			else
			{
				die("Unable to select database." . mysql_error()); //Unable to select the database. Display failure message and exit.
			}
		}
		else
		{
			die("Unable connect to database." . mysql_error()); //Unable to connect to database. Display failure message and exit.
		}
	}
	else
	{
		die("Access Denied!"); //Not a post request. Display Access Denied and exit.
	}
}
else
{
	die("Access Denied!"); //Not a post request. Display Access Denied and exit.
}
?>
Save this file as store.php. Upload this file in the same folder you put setup.php.

Next create a new file in your favourite editor and write the following code:

Code:
<?php
if($_POST) //Make sure it is a post request.
{
	if(isset($_POST["username"]) && isset($_POST["serial"])) //Make sure username and serial are provided.
	{
		$connect = mysql_pconnect("localhost","crorib_admin","userpassword"); //Connect to the database. //Replace the crorib_admin with your username and userpassword with the password you are using for that user. This line connects to the MySQL engine.
		if($connect) //If successfully connected.
		{
			$select = mysql_select_db("crorib_serials",$connect); //Select the database you created. Replace crorib_serials with your database name.
			if($select)
			{
				$user = mysql_escape_string($_POST["username"]); //Variable user that stores our username that was passed as a post request.
				$serial = mysql_escape_string($_POST["serial"]); //Variable serial that stores our serial name for the user that was passed as a post request.
				$GetRows = mysql_query("SELECT * FROM users WHERE Username='$user' AND Serial='$serial'"); //MySQL query that adds the username and serial to the table.
				$RowCount=mysql_num_rows($GetRows); //Count the number of results we have.
				if($RowCount>0)
				{
					die("Correct !");
				}
				else
				{
					die("Incorrect !");
				}
			}
			else
			{
				die("Unable to select database." . mysql_error()); //Unable to select the database. Display failure message and exit.
			}
		}
		else
		{
			die("Unable connect to database." . mysql_error()); //Unable to connect to database. Display failure message and exit.
		}
	}
	else
	{
		die("Access Denied!"); //Not a post request. Display Access Denied and exit.
	}
}
else
{
	die("Access Denied!"); //Not a post request. Display Access Denied and exit.
}
?>
Save this file as load.php. Upload this file in the same folder you put setup.php.

Now, if you want to be able to delete a user from database, create a new file in your favourite editor and write the following code:

Code:
<?php
if($_POST) //Make sure it is a post request.
{
	if(isset($_POST["username"]) && isset($_POST["serial"])) //Make sure username and serial are provided.
	{
		$connect = mysql_pconnect("localhost","crorib_admin","userpassword"); //Connect to the database. //Replace the crorib_admin with your username and userpassword with the password you are using for that user. This line connects to the MySQL engine.
		if($connect) //If successfully connected.
		{
			$select = mysql_select_db("crorib_serials",$connect); //Select the database you created. Replace crorib_serials with your database name.
			if($select)
			{
				$user = mysql_escape_string($_POST["username"]); //Variable user that stores our username that was passed as a post request.
				$serial = mysql_escape_string($_POST["serial"]); //Variable serial that stores our serial name for the user that was passed as a post request.
				$DeleteUser = "DELETE FROM users WHERE Username='$user' AND Serial='$serial'"; //MySQL query that deletes the username and serial from the table.
				if(mysql_query($DeleteUser)) //If deleted successfully
				{
					die("User deleted successfully.");  //Display success message and exit.
				}
				else
				{
					die("Unable to delete user from the database." . mysql_error());  //Unable to add the user. Display failure message and exit.
				}
			}
			else
			{
				die("Unable to select database." . mysql_error()); //Unable to select the database. Display failure message and exit.
			}
		}
		else
		{
			die("Unable connect to database." . mysql_error()); //Unable to connect to database. Display failure message and exit.
		}
	}
	else
	{
		die("Access Denied!"); //Not a post request. Display Access Denied and exit.
	}
}
else
{
	die("Access Denied!"); //Not a post request. Display Access Denied and exit.
}
?>
Save this file as delete.php. Upload this file in the same folder you put setup.php.

Alright, our server side scripting is done now. We now need to code our registration and login application in VB.NET.

Open Visual Basic.NET and create a new Windows Forms Project.

Once you are done with that, create a user interface similar to the following:



Rename the textboxes in the Login groupbox as following:

Username: login_username
Password: login_password

This is how you change the name of the textbox. First select the textbox and then go to the properties panel and change the name field.



Similarly, rename the textboxes in the Create New Account groupbox as following:

Username: reg_username
Email: reg_email



Next, right click your project name in the solution explorer and click Add Reference from the menu:



Wait for a moment. This will open a dialog from where you can choose a reference. Click .NET tab if it isn't already selected and scroll down until you see System.Web component. Select it and press OK.



Now open your class code (Press F7) and add the following imports:

Code:
Imports System.Net
Imports System.Text
Imports System.Web
Imports are always added on top of your code, as shown below:



Next, add the following three functions to your class:

Code:
Function CheckUser(AuthenticationPage As String, Username As String, Serial As String) As Boolean
        Dim wc As New WebClient()
        wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded")
        Dim Data As String = String.Format("username={0}&serial={1}", HttpUtility.UrlEncode(Username), HttpUtility.UrlEncode(Serial))
        Dim ResponseBytes() As Byte = wc.u p l o a d data(AuthenticationPage, "POST", Encoding.ASCII.GetBytes(Data))
        Dim Response As String = Encoding.ASCII.GetString(ResponseBytes)
        If Response.Contains("Correct") Then
            Return True
        Else
            Return False
        End If
End Function
Code:
Function AddUser(StoragePage As String, Username As String, Serial As String) As Boolean
        Dim wc As New WebClient()
        wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded")
        Dim Data As String = String.Format("username={0}&serial={1}", HttpUtility.UrlEncode(Username), HttpUtility.UrlEncode(Serial))
        Dim ResponseBytes() As Byte = wc.u p l o a d data(StoragePage, "POST", Encoding.ASCII.GetBytes(Data))
        Dim Response As String = Encoding.ASCII.GetString(ResponseBytes)
        If Response.Contains("User added") Then
            Return True
        Else
            Return False
        End If
End Function
Code:
Function DeleteUser(DeletionPage As String, Username As String, Serial As String) As Boolean
        Dim wc As New WebClient()
        wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded")
        Dim Data As String = String.Format("username={0}&serial={1}", HttpUtility.UrlEncode(Username), HttpUtility.UrlEncode(Serial))
        Dim ResponseBytes() As Byte = wc.u p l o a d data(DeletionPage, "POST", Encoding.ASCII.GetBytes(Data))
        Dim Response As String = Encoding.ASCII.GetString(ResponseBytes)
        If Response.Contains("User deleted") Then
            Return True
        Else
            Return False
        End If
End Function
In the above functions, remove the spaces between "u p l o a d data". It was sensored by MPGH, so I had to add spaces.

Your class code should look something like this now:



Now go back to the designer (Press Shift+F7) and double click the Login button. This will take you to the Login button's click event code. Add the following code in it:

Code:
If CheckUser("http://mysite.com/authentication/load.php", login_username.Text, login_password.Text) Then
            'Do whatever you want to do on successful login here.
            MsgBox("You have successfully logged in.")
        Else
            'Do whatever you want to do on un-successful login here.
            MsgBox("You have provided invalid username or password. Unable to login.")
End If
So the Login button's code should look like this now:



Note that you have to replace "http://mysite.com/authentication/load.php" with the location of the load.php on your site. If you followed the instructions of this tutorial as is, you'll need to change only mysite.com with your domain name.

Next, we need a couple of functions to generate a random serial / password and sending the email to the user.

First, add the following function to your class:

Code:
Function GenerateRandom(length As Integer) As String
        Dim Rand As New Random()
        Dim Allowed() As Char = "0123456789abcdefghijklmnopqrstuvwxyz"
        Dim SB As New System.Text.StringBuilder
        Do
            SB.Append(Allowed(Rand.Next(0, Allowed.Length)))
        Loop Until SB.Length = length
        Return SB.ToString
End Function
Below this function, add the following variable:

Code:
Dim NewSerial As String = ""
This variable will help us use the same serial for storing in database and for sending in the email.

Now, add the following procedure to your class code:

Code:
Sub SendEmail(sendersemail As String, senderspassword As String, emailusername As String, username As String)
        Dim Title As String = "Your Password for my software xxx"
        Dim Body As String = "Dear " & username & "," & vbCrLf & "Thank you for registering with my software xxx. Your password is: " & vbCrLf & NewSerial & vbCrLf & vbCrLf & "Regards," & vbCrLf & "Pedophile !"
        Dim Message As New Net.Mail.MailMessage(sendersemail, emailusername, Title, Body)
        Dim SMTP As New Net.Mail.SmtpClient("smtp.gmail.com", 587)
        SMTP.Credentials = New Net.NetworkCredential(sendersemail, senderspassword)
        SMTP.EnableSsl = True
        SMTP.Timeout = 100000
        SMTP.Send(Message)
End Sub
The above function takes four parameters. First two parameters require the sender's email and password. You should make a new gmail account for this purpose. Third parameter takes the user's email address and the last parameter takes the user's name.

Alright, our functions are now complete. Go back to the designer (Press Shift+F7) and double click the Create Account button. This will take you to the button's click event. Add the following code in it:

Code:
If (String.IsNullOrEmpty(reg_username.Text.Trim())) Then
            MsgBox("Username cannot be empty.")
            Exit Sub
        End If
        NewSerial = GenerateRandom(10) 'Replace 10 with the desired length of the password.
        If (AddUser("http://mysite.com/authentication/store.php", reg_username.Text, NewSerial)) Then
            MsgBox("You are now added to the database. Sending you your password now on your email address.")
            SendEmail("myemailaddress@gmail.com", "mygmailaccountpassword", reg_email.Text, reg_username.Text) 'Replace first two parameters with your credentials.
        Else
            MsgBox("Something went wrong. Unable to add you to database.")
End If


Note that you have to replace "http://mysite.com/authentication/store.php" with the location of the store.php on your site. If you followed the instructions of this tutorial as is, you'll need to change only mysite.com with your domain name.

Alright, now test your application by running it (Press F5).





The password will be sent to the email. Open your mail and copy the password and then try to login:



That's all. I don't feel like organizing the tutorial as I am tired and have a mid-term exam tomorrow. I'll do it later though.

If you don't understand anything, go fuck yourself.

Cheers,
Hassan
Oh good lord it's a SQL injector's wet dream.
Quote Originally Posted by Jason View Post
Oh good lord it's a SQL injector's wet dream.
LOL true.
Will fix later. Preparing for exam now ! KThnx
Nice tutorial, how can i make it so they only create the account then they have to buy the product through paypal and THEN it will send them their serial, or something like that, because idk what the serial is used for in this case
oh ok wait, by serials in this case you mean password? lol didn't really read that, ok for my earlier question, how can i make it so there will be a way to purchase letsay a product through paypal while they already have an account on the site, it will enable that account for the product, so when they login to the application(the product), if they have purchased it, it will log them in, but if they havent it wont log them in
Quote Originally Posted by dudezone2 View Post
oh ok wait, by serials in this case you mean password? lol didn't really read that, ok for my earlier question, how can i make it so there will be a way to purchase letsay a product through paypal while they already have an account on the site, it will enable that account for the product, so when they login to the application(the product), if they have purchased it, it will log them in, but if they havent it wont log them in
You will need to alter the table structure and add columns like IsActivated. When they will purchase your software, you will execute a query that will set this value to true. Then from your load.php script file you will check this value and if it is set to true, you will return the 'Activated' or 'Correct !' message which means the user is ready to login. If you want a spoonfeed, wait till Saturday night !
Lol i'd like a spoonfeed haha, sorry but i have no idea what to do with php and mysql stuff, i guess i'll wait, Thanks

EDIT: oh and for the tutorial, maybe add in the adduser thing if the user already exists, because you can reregister with the same username and email
Whats the code for changing a users password - oh and deleting a user, because it says u need the serial but if it generates a random serial how do i know the serial of the user im deleting?
Quote Originally Posted by dudezone2 View Post
Whats the code for changing a users password - oh and deleting a user, because it says u need the serial but if it generates a random serial how do i know the serial of the user im deleting?
I'll guide you on Teamviewer or MSN later.
Good Job ! But i have one question what if you havent NETFRAMEWORK 2 ? i have netframework 4 and i havent system.web ?

Thanks
Quote Originally Posted by ajdo773 View Post
Good Job ! But i have one question what if you havent NETFRAMEWORK 2 ? i have netframework 4 and i havent system.web ?

Thanks
You can just simply download the System.Web DLL and use it ?
You'll already have the System.Web namespace, you just need to filter which framework you look for references in (when you go to the "Add Reference" menu, you'll see it says "filtered for .NET 4.0" or something similar). The System.Web is made for .NET 3.5 (though it's still perfectly valid for use in .NET 4.0). It's some weird shit with VS2010.
Code:
function db_escape($values, $quotes = true) {
    if (is_array($values)) {
        foreach ($values as $key => $value) {
            $values[$key] = db_escape($value, $quotes);
        }
    }
    else if ($values === null) {
        $values = 'NULL';
    }
    else if (is_bool($values)) {
        $values = $values ? 1 : 0;
    }
    else if (!is_numeric($values)) {
        $values = mysql_real_escape_string($values);
        if ($quotes) {
            $values = "'" . $values . "'";
        }
    }
    return $values;
}

$_POST = db_escape($_POST,true);
This should fix a few Injection-Problems
I don't like your PHP conventions.
Don't you think.
Code:
<?php

$mysql_host = "localhost";
$mysql_username = "crorib_admin";
$mysql_password = "password";
$mysql_database = "crorib_serials";

$connect = mysql_connect($mysql_host, $mysql_username, $mysql_password);
if($connect) {
	$select = $mysql_select_db($mysql_database, $connect);
	if($select) {
		$query = "CREATE TABLE users (username varchar(255), serial varchar(500))"; 
		if(mysql_query($query)); {
			die ('Table created successfully. You can delete setup.php now.');
		} else {
			die ("Failed to create the table. ".mysql_error());
		}
	} else {
		die("Unable to select database.".mysql_error());
	}
} else {
	die('Failed to connect.'.mysql_error());
}
?>
and

Code:
<?php

$mysql_host = "localhost";
$mysql_username = "crorib_admin";
$mysql_password = "password";
$mysql_database = "crorib_serials";

$username = $_POST['username'];
$serial = $_POST['serial]; 

if(isset($username) && isset($serial")) {
	$connect = mysql_connect($mysql_host, $mysql_username, $mysql_password);
	if($connect) {
		$select = mysql_select_db($mysql_database, $connect); 
		if($select) {
			$query = "INSERT INTO users VALUES (mysql_escape_string($username), mysql_escape_string(serial))";
			if(mysql_query($query)) {
				die("User added successfully.");
			} else {
				die("Unable to add user to the database.".mysql_error());
			}
		} else {
			die("Unable to select database.".mysql_error());
		}
	} else {
		die("Unable connect to database.".mysql_error());
	}
} else {
	die("Access Denied!");
}
?>
Look much better. (I know I only did 2).
Quote Originally Posted by Nathan
Code:
} else {
You need to be put down.
Posts 1–15 of 32 · Page 1 of 3

Post a Reply

Similar Threads

Tags for this Thread

Need help?