Welcome to Ramleague,

Ramleague - the best site for pinoy chat, games chat and mobiles chat,

Sign Up
  1. Hello guest Guest , Are you tired from Ads? to remove some ads you need to register and be active. :D

[Tutorial] VB.NET + MySQL + PHP Registration And Login

Discussion in 'Visual Basic Programming' started by Dynasty, Nov 3, 2017.

  1. Dynasty 그래픽 아티스트
    Member Lvl2

    Dynasty
    Joined:
    Jan 13, 2015
    Gender:
    Male
    Posts:
    617
    Reputation:
    317
    Thanks:
    174
    Location:
    Hell
    Devilish
    Iraq
    LukeXD
    Dynasty
    Skype name: Dynasty
    Dynasty
    Dynasty
    Dynasty

    VB.NET + MySQL + PHP Registration And Login

    Hi i would like to share this tutorial, its very useful for those would like to setup there own Forum Login system in app
    PS : i don't own every single words from the tutorial below, just leave a reply if you found issues.

    Tutorial by Hassan <3


    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 (Please Login/Register to view links) 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:

    [​IMG]
    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.

    [​IMG]
    If the Database creation is successful, you will see a notification like the following:

    [​IMG]
    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:

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

    [​IMG]
    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:

    [​IMG]
    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".

    [​IMG]
    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
    [​IMG]

    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:

    [​IMG]
    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.

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

    [​IMG]
    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.
    [​IMG]

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

    [​IMG]
    On the bottom of the page, you will see a success message:

    [​IMG]
    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:

    Please Login/Register to view links

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

    [​IMG]
    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:

    [​IMG]
    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.

    [​IMG]
    Similarly, rename the textboxes in the Create New Account groupbox as following:

    Username: reg_username
    Email: reg_email

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

    [​IMG]
    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.

    [​IMG]
    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.uploaddata(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.uploaddata(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.uploaddata(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
    Your class code should look something like this now:

    [​IMG]
    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("https://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 "Please Login/Register to view links" 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("https://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("[email protected]", "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 "Please Login/Register to view links" 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:

    Tutorial by
    Hassan
     
    • BE A GAMER - RAMLeague
Loading...

Advertisement

Similar Threads Forum Date
SQL DXP for Oracle and MySQL 6.6.0.170 PC Apllications Dec 28, 2021
SQL DXP for Oracle and MySQL 6.6.0.170 PC Apllications Dec 28, 2021
SQL DXP for SQL Server and MySQL 6.6.0.180 PC Apllications Dec 28, 2021
SQL DXP for Oracle and MySQL 6.6.0.170 PC Apllications Dec 28, 2021
SQL Delta for MySQL 6.6.0.105 PC Apllications Dec 28, 2021
SQL Delta for MySQL 6.6.0.105 PC Apllications Dec 28, 2021

Tags for this Thread

:

Share This Page