operations |
comment | "parent_author":"",<br>"parent_permlink":"utopian-io",<br>"author":"mrtega",<br>"permlink":"building-personalised-web-applications-with-php-and-mysql-1-introduction",<br>"title":"BUILDING PERSONALISED WEB APPLICATIONS WITH PHP & MySQL (#1) - INTRODUCTION",<br>"body":"#### Repository\nhttps:\/\/github.com\/php\/php-src\n\n#### What will I learn? \n\n - You will be introduced to building web applications using PHP and MySQL.\n - You will learn to work with personal data.\n - You will learn how to securely input data into your database.\n - You will learn to create sign up form\n - You will learn to create\/edit a user profile page on this tutorial . \n\n\n#### Requirements \n\n - Basic knowledge of HTML,<br> CSS,<br> PHP programming language\n - A web server,<br> I will be using XAMPP\n - A web browser\n - Text editor\n\n#### Difficulty \n\n - Basic\/Intermediate \n\n#### Tutorial Contents \n\n![2000px-PHP-logo.svg.png (https:\/\/cdn.steemitimages.com\/DQmR4UpnK26NaqpLYJyfFsZzDxqGqBTyJW8q7BgDytGYeVh\/2000px-PHP-logo.svg.png)\nhttps:\/\/en.wikipedia.org\/wiki\/PHP\n\nCreating a web application with a sense of membership (meaning that users interact with it in a personal way) might seem like a difficult task at first. If you ever wanted to do this by yourself,<br> then this post is for you. We are going to be dealing with every aspect of creating a membership based site,<br> with a secure members area protected by users password.\n\nThe whole process consists of two major parts: user registration and user authentication. In the first part,<br> we are going to cover creation of the sign-up form and storing the data in a MySQL database. In the later tutorials,<br> we will create the login\/logout form and use it to allow users in and out secure areas on our web application.\n\nMuch of the websites have a registration form for your users to sign up and thus may benefit from some kind of privilege within the site. In this tutorial we will see how to create a registration form in PHP and MySQL. We are going to name our web application **mywebapp** that's what we will be creating through out this tutorial. Let's start;\n\n##### Setting the database;\nFor this tutorial I will be working with a local server using xampp to access phpmyadmin ,<br> you might be using a different web server but it shouldn't be hard to keep up. We start by setting up a new database,<br> I'm going to call mine 'mywebapp' . Once this is done we go further to create a new table on the database,<br> this is where all the user data would go in. I'm going to call my table `web_user` ,<br>you can create yours with a name of your choice. The `web_user` table would be made up of seven columns representing information about a user,<br> each row of the table contains personal data for a single user. The sql code to create and set up table is written below\n\n```\nCREATE TABLE `web_user` (\n `user_id` INT AUTO_INCREMENT,<br>\n `join_date` DATETIME,<br>\n `username` VARCHAR(32),<br>\n `email` VARCHAR(32),<br>\n `confirmed` VARCHAR(32),<br>\n `confirm_code` VARCHAR( 32 ) ,<br>\n PRIMARY KEY (`user_id`)\n);\n\n```\n\n##### Setting the index page\n The indexpage of `mywebapp` for now would contain a link telling the user to sign up and log in .\n\n We are going to start by connecting our indexpage to the database,<br> since we are going to be doing this for all our pages it is better to have this code stored in a separate script to avoid duplication of codes,<br> this also helps to solve the issue of having to make changes in several scripts when you can just do this for one,<br> and it will affect the other scripts.\n\n The indexpage of `mywebapp` will comprise of links telling users to signup and login we will be discussing the sign up process on this tutorial. The html code for the index page is \n\n```\n<\/head>\n<body id = \"body\">\n <h1>mywebapp - Let Love Lead<\/h1>\n\n<?php\n \n\n echo '❤ <a href=\"login.php\">Log In<\/a><br \/>';\n echo '❤ <a href=\"signup.php\">Sign Up<\/a>';\n \n\n?>\n\n<\/body> \n``` \ncss\/style.css - This is for stylesheet for ``index.php`,<br> `signup.php` and further pages.\n\n```\n.error \n font-weight: bold;\n color: #FF0000;\n \n\n\nform label \n display: inline-block;\n width: 150px;\n font-weight: bold;\n\n \n\n.correct \n font-weight: bold;\n color: 0000ff;\n font-family:'Fauna One',<br>serif;\n text-align:center\n align: center;\n \n\n\nh1 \nmargin-top:0;\ncolor:#fff;\n\ntext-align:center;\nwidth:100%;\nheight:50px;\n\n \n\ninput \nmargin-top:10px;\nbox-shadow:0 1px 1px 0 #a9a9a9\n \n\ninput[type=submit \n\t\nborder:1px solid #fff;\nfont-family:'Fauna One',<br>serif;\nfont-weight:700;\nfont-size:18px;\nmargin-left:60px;\nmargin-bottom; 20;\n \n\ntd.label \n font-weight: bold;\n \n\nimg.profile \n vertical-align: top;\n \n\n#body \n\tbackground-color:#cdcdcd;\n\t\n \n\n#form \nbackground-color:#00dfdf;\ncolor:#000000;\nbox-shadow:0 1px 1px 1px gray;\nfont-weight:400;\nwidth:480px;\nmargin:70px 0 0;\njustify-content: center\nheight:300px\n\n \n\n#mainform \nwidth:960px;\nmargin:30px auto;\npadding-top:20px;\nfont-family:'Fauna One',<br>serif;\ntext-align:center\nalign: center;\nmargin-top: 20px;\nmargin-bottom: 20px;\n\n \n```\nThis the image of the indexpage\n\n![Screenshot (125).png (https:\/\/cdn.steemitimages.com\/DQmWfxTjRW3D9fjQZts22YS53RqmLJRV3mEGni7tuDCZZUq\/Screenshot%20(125).png)\n\n##### Setting up the registration page\nOnce the index page is created,<br>the next is to make sure users are able to signup. In order to create a user account,<br> we need to gather a minimal amount of information from the user. We need their email address and their desired username and password. Of course,<br> we can ask for more information at this point,<br> but a long form is always a turn-off,<br> the user will have the opportunity to provide addition info once they signed up . We use our HTML knowledge to create the form field in the `signup.php` .\n\n```\n\n <div align = \"center\" id=\"mainform\">\n <h3>Please enter your username and desired password to sign up to mywebapp.<h3>\n <form method=\"post\" id=\"form\" action=\"<?php echo $_SERVER['PHP_SELF' ; ?>\">\n <fieldset>\n <legend>Registration Info<\/legend>\n <label for=\"username\">Username:<\/label>\n <input type=\"text\" id=\"username\" name=\"username\" value=\"<?php if (!empty($username)) echo $username; ?>\" \/><br \/>\n\t <label for=\"email\">Email address:<\/label>\n <input type=\"text\" id=\"email\" name=\"email\" value=\"<?php if (!empty($email)) echo $email; ?>\" \/><br \/>\n <label for=\"password1\">Password:<\/label>\n <input type=\"password\" id=\"password1\" name=\"password1\" \/><br \/>\n <label for=\"password2\">Password(retype):<\/label>\n <input type=\"password\" id=\"password2\" name=\"password2\" \/><br \/>\n <\/fieldset>\n <input type=\"submit\" value=\"Sign Up\" name=\"submit\" \/>\n <\/form>\n <\/div>\n```\nThis is the image of the Sign-up page\n\n![Screenshot (120).png (https:\/\/cdn.steemitimages.com\/DQmQNr1jraEbUf74jjjUPoVNQ2XNpTZSWuFE8n3K6cvk89H\/Screenshot%20(120).png)\n\n Let's now implement the feature that will receive information submitted from the form about a user and store the information in the `web_user` table created in the `mywebapp` database. This code will be in the `signup.php` file.\n\n we connect the `signup.php` code to our database,<br> you can do this by using this method\n```\nmysql_connect(\"localhost\",<br> \"root\",<br> \"password\") or die(mysql_error()); \/\/ Connect to database server(localhost) with username and password.\nmysql_select_db(\"mywebapp\") or die(mysql_error()); \/\/ Select registration database.;\n```\nOr you can use this other method,<br> once you have all your database information stored in a file like `connect.php`. You use `require_once() `statement to include the php file to avoid duplication of codes.\n\n```\n require_once('connect.php');\n\n ```\n Connect.php defines the database constants for mywebapp\n```\n<?php\n \/\/ database connection constants\n define('HOST',<br> 'localhost');\n define('USER',<br> 'root');\n define('PASSWORD',<br> 'password');\n define('NAME',<br> 'mywebapp');\n?>\n```\n\n\n The `trim()` function gets rid of leading and trailing spaces in this form data. The real weakness that SQL injections capitalize on is form fields that aren't validated for dangerous characters(this are characters that could potentially change the nature of an SQL query). The `mysql_real_escape_string()` function escapes special characters in a string for use in an SQL statement. Putting the `trim()` and the `mysql_real_escape_string()` provides a solid line of defence in collecting users data to the database\n\n```\n $username = mysqli_real_escape_string($dbc,<br> trim($_POST['username' ));\n $email = mysqli_real_escape_string($dbc,<br> trim($_POST['email' ));\n $password1 = mysqli_real_escape_string($dbc,<br> trim($_POST['password1' ));\n $password2 = mysqli_real_escape_string($dbc,<br> trim($_POST['password2' ));\n $code = mysqli_real_escape_string($dbc,<br> trim($_POST['code' ));\n```\n We go further to carry out our form validation and ensure the form is filled properly,<br> with the right information.\n\nWe make sure none of the form filed is left empty,<br> else the program wont run and the user would me told to enter all of the sign-up data.\n```\n\tif (!empty($username) && !empty($username) && !empty($email) && !empty($email) && !empty($password1) && !empty($password2) && ($password1 == $password2)) \n else \n echo '<p class=\"error\">You must enter all of the sign-up data.<\/p>';\n \n\t \n \n```\nNext we make sure someone isn't already registered using this username,<br> so we check our table to see if the username has been used before,<br> If yes it wont run and the user would be told to try another username. Also before the data is sent to the `web_user` table we encrypt the users password using the `SHA()` function to produce a 32 bit password ,<br>that anyone with access to the table cant decrypt.\n``` \n if (!empty($username) && !empty($username) && !empty($email) && !empty($email) && !empty($password1) && !empty($password2) && ($password1 == $password2)) \n \/\/ Make sure someone isn't already registered using this username\n $query = \"SELECT * FROM web_user WHERE username = '$username'\";\n\t \n $data = mysqli_query($dbc,<br> $query); \n \n if (mysqli_num_rows($data) == 0) \n \/\/ The username is unique,<br> so insert the data into the database \n $query = \"INSERT INTO web_user (username,<br> password,<br> join_date,<br> email,<br> confirmed,<br> confirmcode) VALUES ('$username',<br> SHA('$password1'),<br> NOW(),<br> '$email',<br> '0',<br> '$confirmcode')\";\n mysqli_query($dbc,<br> $query);\n\n else \n \/\/ An account already exists for this username,<br> so display an error message\n echo '<p class=\"error\">An account already exists for this username. Please use a different address.<\/p>';\n $username = \"\";\n \n\t \n\n```\nNext we make sure that the email address entered is in the correct email format,<br> in PHP this code can be used to verify that,<br> its a small code gotten from `php.net`. If it doesnt meet the standard the expression returns false,<br>and an error message pops up. \n```\n\t if(eregi(\"^[_a-z0-9- +(\\.[_a-z0-9- +)*@[a-z0-9- +(\\.[a-z0-9- +)*(\\.[a-z 2,<br>3 )$\",<br> $email)) \n else \n echo '<p class=\"error\">Invalid email address.<\/p>'; \n \n \n``` \n \n##### Email Verification for New Users\n Once the submitted account details has been entered to our database,<br> its time to generate an activation code that will be sent to the users email address.\nIn our table we created a column called `confirmcode`,<br> this code is a string of numbers generated at random. We also send this code to the user's email address. They then can click the link (which contains the code) and we will verify if it matches up with the one in the database. Let's create a local variable called `$confirmcode` and generate a random code. We should also take note of the fact that once all the registration data are fine we created a query that inserts '0' into the `confirmed` column of the database,<br> this shows that a user has been registered but not confirmed yet,<br> and once the `$confirmcode` from the users mail matches that in the web_user table the query inserts '1' into the `confirmed` column in the users role. \n\n```\n $confirmcode = rand() ; \/\/ Generate random variable characters and assign it to a local variable.\n```\n Now that the information is in our database ,<br> we need to send an email to the user with the verification link. So we make use of the PHP 'mail' function to do that\n\n```\n $message =\n\t\t \n\t\t \"\n\t\t Confirm your email\n\t\t Click the link below to verify your account\n\t\t \n\t\t http:\/\/localhost\/mywebapp\/emailconfirm.php?username=$username&confirmcode=$confirmcode\n\t\t \";\n\t\t \n\t\t mail( $email,<br>\"Mywebapp confirm Email\",<br> $message,<br>\"From: [email protected]\");\n```\nThis the full php code below\n```\n<?php\n \n require_once('connect.php');\n\n \/\/ Connect to the database\n $dbc = mysqli_connect(DB_HOST,<br> DB_USER,<br> DB_PASSWORD,<br> DB_NAME);\n\n if (isset($_POST['submit' )) \n \/\/ Grab the profile data from the POST\n $username = mysqli_real_escape_string($dbc,<br> trim($_POST['username' ));\n $password1 = mysqli_real_escape_string($dbc,<br> trim($_POST['password1' ));\n $password2 = mysqli_real_escape_string($dbc,<br> trim($_POST['password2' ));\n\t$email = mysqli_real_escape_string($dbc,<br> trim($_POST['email' ));\n \n\t $confirmcode = rand();\n\t \n\t if (!empty($username) && !empty($username) && !empty($email) && !empty($email) && !empty($password1) && !empty($password2) && ($password1 == $password2)) \n \/\/ Make sure someone isn't already registered using this username\n $query = \"SELECT * FROM web_user WHERE username = '$username'\";\n\t \n $data = mysqli_query($dbc,<br> $query);\n\t \n\t if(eregi(\"^[_a-z0-9- +(\\.[_a-z0-9- +)*@[a-z0-9- +(\\.[a-z0-9- +)*(\\.[a-z 2,<br>3 )$\",<br> $email)) \n \n \n if (mysqli_num_rows($data) == 0) \n \/\/ The username is unique,<br> so insert the data into the database\n $query = \"INSERT INTO web_user (username,<br> password,<br> join_date,<br> email,<br> confirmed,<br> confirmcode) VALUES ('$username',<br> SHA('$password1'),<br> NOW(),<br> '$email',<br> '0',<br> '$confirmcode')\";\n mysqli_query($dbc,<br> $query);\n\t\t\n\t\t $message =\n\t\t \n\t\t \"\n\t\t Confirm your email\n\t\t Click the link below to verify your account\n\t\t \n\t\t http:\/\/localhost\/mywebapp\/emailconfirm.php?username=$username&confirmcode=$confirmcode\n\t\t \";\n\t\t \n\t\t mail( $email,<br>\"Mywebapp confirm Email\",<br> $message,<br>\"From: [email protected]\");\n\n \/\/ Confirm success with the user\n echo '<p class=\"correct\">Your account has been made,<br><br\/> please verify it by clicking the link that has been sent to your email. <\/p>';\n\n mysqli_close($dbc);\n exit();\n \n\t \n\t \n else \n \/\/ An account already exists for this username,<br> so display an error message\n echo '<p class=\"error\">An account already exists for this username. Please use a different address.<\/p>';\n $username = \"\";\n \n\t \n\t else \n echo '<p class=\"error\">Invalid email address.<\/p>'; \n \n\t \n else \n echo '<p class=\"error\">You must enter all of the sign-up data.<\/p>';\n \n\t \n \n\n mysqli_close($dbc);\n?>\n```\nThe image below signifies what happens once a user clicks the submit button and all the information are filled properlly\n\n![Screenshot (121).png (https:\/\/cdn.steemitimages.com\/DQmNchppWd4qrzJ2B7Kyp1KoxsrXDKeGwAYLyBq5Qf13g4c\/Screenshot%20(121).png)\n\nThe image below shows what the link should look like\n\n![Screenshot (126).png (https:\/\/cdn.steemitimages.com\/DQmbV7GBYy1N11Ukg12cuLqcQSvhSnJorUzGNN6SmmyQZqh\/Screenshot%20(126).png)\n\n##### Account Activation\nThe next step is to activate the account,<br> all we need to do is to create a new link,<br> I called mine `emailconfirm.php`,<br> this basic function of this link would be to confirm the users email address and confirm their account,<br> so they can login.\n\nThe first step would be to grab the `$username` and `$confirmcode` from the link sent to the user,<br> once this is successful we go ahead and collect the `username` and `confirmcode` from the users row on the `web_user` table.\n\n```\nif(isset($_GET['username' ) && !empty($_GET['username' ) AND isset($_GET['confirmcode' ) && !empty($_GET['confirmcode' )) \n\t\n\t$username = mysql_escape_string($_GET['username' ); \/\/ Set email variable\n $confirmcode = mysql_escape_string($_GET['confirmcode' ); \/\/ Set confirm variable\n \n $search = mysql_query(\"SELECT username,<br> confirmcode,<br> confirmed FROM web_user WHERE username='\".$username.\"' AND confirmcode='\".$confirmcode.\"' AND confirmed='0'\") or die(mysql_error()); \n $match = mysql_num_rows($search);\n else \n \/\/ Invalid approach\n echo '<p>Invalid approach,<br> please use the link that has been sent to your email.<\/p>';\n \n\n```\n\nOnce this is done we go further to match the `$username` & `confirmcode`gotten from the link with `username` & `confirmcode `that we already have on our users table. If this code matches,<br> the user is then confirmed and the users `confirmed` column on the database is changed to '1' ,<br>this means that the user has been activated and can now login,<br> and if its invalid an error message would be shown.\n\n```\n<?php\n\nmysql_connect(\"localhost\",<br> \"root\",<br> \"\") or die(mysql_error()); \/\/ Connect to database server(localhost) with username and password.\nmysql_select_db(\"mywebapp\") or die(mysql_error()); \/\/ Select registration database.;\n\nif(isset($_GET['username' ) && !empty($_GET['username' ) AND isset($_GET['confirmcode' ) && !empty($_GET['confirmcode' )) \n\t\n\t$username = mysql_escape_string($_GET['username' ); \/\/ Set email variable\n $confirmcode = mysql_escape_string($_GET['confirmcode' ); \/\/ Set confirm variable\n \n $search = mysql_query(\"SELECT username,<br> confirmcode,<br> confirmed FROM web_user WHERE username='\".$username.\"' AND confirmcode='\".$confirmcode.\"' AND confirmed='0'\") or die(mysql_error()); \n $match = mysql_num_rows($search);\n\n\tif($match > 0) \n \/\/ We have a match,<br> activate the account\n mysql_query(\"UPDATE web_user SET confirmed='1' WHERE username='\".$username.\"' AND confirmcode='\".$confirmcode.\"' AND confirmed='0'\") or die(mysql_error());\n echo '<p class=\"correct\">Your new account has been successfully created. You\\'re now ready to <a href=\"login.php\">log in<\/a>.<\/p>';\n else \n \/\/ No match -> invalid url or account has already been activated.\n echo '<p class=\"error\">This link has already been used.<\/p>';\n \n \n else \n \/\/ Invalid approach\n echo '<p>Your approach was invalid,<br> please use the link that was sent to your email.<\/p>';\n \n\n?>\n\n```\nYou can now login once the link is confirmed \n\n![Screenshot (124).png (https:\/\/cdn.steemitimages.com\/DQmWZ32BHCD88Erx5bey36zscsiBk7jhdxUiKmQfPaGaQQu\/Screenshot%20(124).png)\n\n\n #### CONCLUSION\nIn conclusion we have been able to show that we can use PHP & MySQL to develop a personalised web application which will comprise of a signup form with email verification,<br> in our next tutorial we will be dealing with creating a login page and editing a users profile .\n\n#### Proof of work done\nhttps:\/\/github.com\/mrtega\/mywebapp",<br>"json_metadata":" \"tags\":[\"utopian-io\",<br>\"tutorials\",<br>\"php\",<br>\"programming\",<br>\"open-source\" ,<br>\"image\":[\"https:\/\/cdn.steemitimages.com\/DQmR4UpnK26NaqpLYJyfFsZzDxqGqBTyJW8q7BgDytGYeVh\/2000px-PHP-logo.svg.png\",<br>\"https:\/\/cdn.steemitimages.com\/DQmWfxTjRW3D9fjQZts22YS53RqmLJRV3mEGni7tuDCZZUq\/Screenshot%20(125).png\",<br>\"https:\/\/cdn.steemitimages.com\/DQmQNr1jraEbUf74jjjUPoVNQ2XNpTZSWuFE8n3K6cvk89H\/Screenshot%20(120).png\",<br>\"https:\/\/cdn.steemitimages.com\/DQmNchppWd4qrzJ2B7Kyp1KoxsrXDKeGwAYLyBq5Qf13g4c\/Screenshot%20(121).png\",<br>\"https:\/\/cdn.steemitimages.com\/DQmbV7GBYy1N11Ukg12cuLqcQSvhSnJorUzGNN6SmmyQZqh\/Screenshot%20(126).png\",<br>\"https:\/\/cdn.steemitimages.com\/DQmWZ32BHCD88Erx5bey36zscsiBk7jhdxUiKmQfPaGaQQu\/Screenshot%20(124).png\" ,<br>\"links\":[\"https:\/\/github.com\/php\/php-src\",<br>\"https:\/\/en.wikipedia.org\/wiki\/PHP\",<br>\"https:\/\/github.com\/mrtega\/mywebapp\" ,<br>\"app\":\"steemit\/0.1\",<br>\"format\":\"markdown\" " |
|