PHP Day 14

Day 14



(Complete code of Day 14 and 15 is at the end of this word document.)

Welcome to day 14 of PHP in 15 Days – Guaranteed training course. From Today we are going to start developing a small website that will have dynamic data for site visitors as well as a fully functional control panel for admin and author role type users.This will really help you learn how to develop a dynamic website systematically and will give you an insight of a real life project. Let’s have a look what kind of functionality we are going to develop for the Control Panel. So here is the final product we will be developing in these two final days of this course.

I am not going in any kind of styling right now, but this will mainly consist of the code that we are concerned to specifically that is PHP.

Control Panel:

So, this is the main and landing page where any of our admin or author will land. Our site name will be an imaginary name that is article-site and within this site we have created a folder that is mainly devoted to our admins and authors and the name of that is crud.

From this page as you can see this is a form prompting to login, admin/author will be able to login to their dashboard if they are already registered and activated with us. Otherwise they need to register first from the link above here. Let’s login with credential of an admin role. After being logged-in, you can see the admin will be shown the welcome message with his name as well as his profile containing some of his own information. Below here is a link to update profile.

Above here, you can see different links like, all users, let’s click it and it’s taking us to a page where admin can view all the users registered. One thing to keep in mind that this is admin, who is logged-in right now so, he has the privilege to view all registered users. Here is the status of one particular user and both of these are active right now. When any of these will not be active or pending that is awaiting for approval, here in the action column a link will appear from where, an admin can activate any ofthe pending user.

From this link above that is control panel, admin can go back to the main screen of his dashboard. Admin can update his own profile by clicking this link below and you can see it’s taking us to the page where admin will be able to update his own profile. Let’s make a little change here and you can see after clicking update button it’s prompting us to the main page where the change is visible. Let’s change it back to the previous position and off course admin can logout by clicking this logout button and you can see after being logged out no one can even see the links of dashboard.

Now let’s login with a user credential whose role is an author only and not an admin.So, let’s login and this is the dashboard of an author. Very much similar to the admin dashboard as welcome message as well as profile and update profile link or button. Up here you can see a link Submit Article and another one View Articles and a same button Control Panel that we saw in admin control panel and logout button. Here is no any all users link to view all registered user as this is author dashboard. So, he has not permission to view that. Now, let try to click submit article. From here the author will be able to write and submit an article. Let’s give a title here and put a name for this article. Both of these, may be more or less are the same thing but can be used for different purposes as one of them can be used to show to the site visitors as title of the article and name can be displayed to the author within the article lists of his own articles to remember this particular article. That’s up to you, how you plan it. In this text box all the content of the article can be written and click publish to publish it to the site and you can see a success message is displayed to the author.

Now let’s click this ‘View Articles’ link and here author will be able to view all of his own written and published articles with their, article name, title and content. Click on Control Panel link and it will take author to the main screen. Update profile button can update his own profile and let’s check it out as well. This is the same as we saw in admin Control Panel. Let’s change name here and click update and we are sent to the main page and you can see the change in welcome message. And off-course author can logout by clicking on this logout button.

Now let’s go to the site that will be available to our site visitors by just removing this extra link from here and only the name of our site that is article-site. Push enter button from your keyboard and we are on the main index page of our site. Welcome message at the top and a link to home page that is this very page. Each article’s title and summary or teaser of the content and a read more button or link. Another article with title, teaser and read more and another article’s title, teaser and read more link.

So, when we click the read more button or link this takes the visitor of our site to the full view of this single article. Here on this page, full title of this one article and full content of this article as well as the author name who wrote this article. At the top there is home link and by clicking this visitors can go back to the main page of our site.

This is all for the glimpse of what we are going to developin these two final days of this course. Let’s start developing this all from scratch.

So, we are going to create crud first that will hold all the functionality for admin and author which will create and develop contents for the main site. Let’s go to our XAMPP installation folder and to htdocs and here I am going to create a new folder named crud. Now open any of your code editor, I am using PHPStorm and from the file menu let’s go to our recently created folder crud. Now we are in crud where I am going to create the whole functionality for admins and authors. So, here we need some of the files to create the functionality so, let’s first create few of these. So, first file we need is login, from where any registered user will be able to login to the control panel. Second one is registration to let anyone register with us. So, both of these files are basically going to hold forms, that will be filled and submitted by users. Another file we need is update_profile to let our registered users update their profile. We also need the page that will be displayed when user will be loggedin and that will be the first main page for control panel.Let’s create it and name it‘index.php’. Keep in mind that all of these are going to have extension php as we opt to create a new php file and the extension php is automatically given to them.

So, now let’s start coding in registration.php file. This is a registration form, so to save time, here is just a simple HTML registration form containing name, email, username, password and password again fields to fill out. One new field and that is ‘agree to our terms of service’ that is a check box and two input fields that are submit button and reset button. Within name, email and username I have supplied some php code for user-friendlinessthat is capable to show the form data. When user will submit form, if he commits with any error the data of these fields will be presented backto him and he wouldn’t need to fill that again.

Now let’s go to the browser and view our form. So, here is the form we just created. But we have not written any php code yet, so, let’s fill this form with some data and submit and nothing happened at all, even no data was given back to the fields of this form as we have no php code yet. Let’s create our PHP code for this form now.

So, we will receive the data here and process it in this area on this same page. So, as we are going to receive data from client side we need to sanitize it first. Let’s create another php file and name it as sanitize and we need only one function here to sanitize data as we created before. Let’s create a function and name it sanitize and then parenthesis and then curly braces. Now between parentheses we will supply some data as argument, so, let’s place an argument here $data. In the execution area we are going to use three internal functions, trim, stripslashes and htmlspecialchars and all of these three will be executed on supplied data.So, put $data here. Store this sanitized data in a variable $data, you can nameboth of these alike, no issues at all. Finally return this $data out of this function so we can use this data for further processing.

Get back to the registration.php page and start a conditional satatment that, if the form has been submitted only then we will proceed further. Let’s just echo ‘Form was submitted’ to check if everything is working fine. Otherwise, echo ‘form was not submitted’. Let’s go to the browser to verify form submission. Refresh the browser and you can see else part of our conditional statement ran as no form has been submitted. So, let’s push the submit button and you can see ‘form was submitted’ message. So, now we can write real code for this registration form submission. Let’s delete all of this except if statement. As we would run this php code only if the form would have been submitted. Otherwise, nothing will happen here.

Now within if condition’s execution area, let’s grab the form data supplied by the user from $_POST array and store them in variables. Let’s create an errors array and keep it empty for now. This array will store the errors if generated any and then we will show all those errors from this array below near the start of the form. Let’swrite if condition for each mandatory field in case it’s empty we will store an error in our errors array. For ‘Password again’ field we will check two conditions whether it’s empty or not equals to password field, in case any of these returns true, an error will be stored in errors array.

$terms will not be checked and verified like we checked other fields, as it’s a check box and it will be only created and available in $_POST array when it will be checked by user. So, we need to tackle this differently. We need to check it’s availability in $_POST array, so we need to check it directly in if condition and we don’t need to sanitize it as it’s purpose is just to check, if it was checked by user or not. So, let’s just check it’s availability in if condition and we don’t need this portion of code, just erase it.

So, let’s go to the browser and check the functionality of our code we wrote till now. Let’s put some dummy data and hit ‘Register’ and nothing happened and no errors as well. It means our code is not generating any errors. Now when the user hits ‘Register’ we need to show him different messages for the fields he left empty. So, let’s create this now. So, right above the start of this form here, let’s start the php tags and write a conditional statement that if count, $errors means if errors array has something in it and counting of that something is greater than 0, only then proceed. In the execution area we are going to run a foreach-loop that’s going to dig out all the values of this array and we will display them by echo statement, and just append a br tag to show errors line by line if more than one.

So, this code will check if the errors array has values more than 0 then it will run and a foreach loop will start that is given the errors array and it will grab all the values out of it and we are showing each value that is error to the registrant. Little mistake here, just correct it.

Now, let’s go to the browser and refresh and put some dummy data in the form fields and hit register and you can see we get the errors for the fields we left empty. Now, let’s provide password and hit register and we get the error message ‘password again is required and must match the password’ and you must agree to our terms of service. Now, let’s give the password and match the password in password again field and let’s just agree to the terms of service as well. Hit register and now, you can see that we don’t get any errors. Now, we would like to register this user if and only if no errors occur. It means if all the form fields were filled by this user properly and terms of service check-box was checked only then we will register this user. So, we need to place a check here by a conditional statement, if, count of errors array is equals to 0, means if no error was stored in errors array only then we will proceed. And here in this execution area we will register this user, means we will run an insert query here. So, to interact with mysql we need to create a database, table and connection off-course. So, we are going to create database for our site in the next movie.

 



Creating Database for new site:

So, now we are going to create a new database for our new upcoming & under construction website. Here we are in phpMyAdmin and let’s just click ‘New’ and give it a name that is ‘crud’ and click ‘create’ button and the database has been created. Let’s click it to go inside this database and now it’s prompting us to create a new table as it’s empty right now. As we are going to create a functionality where users can register with us and will login to their control panel, so we need a table that will store our users’ information. Let’s create and give it a name ‘users’ and keep the number of the columns to 7 and click ‘Go’ and now we need to name all the columns and define the structure.

First column is going to hold the ids of users so name it as ‘userID’ and make it PRIMARY as well as auto increment, so that it can store unique values by incrementing by one for each record inserted in this table. Next column is going to store names of users, so name it as ‘name’ and set it’s data-type to varchar and length to 40. Next column is going to hold usernames so name it as ‘username’ and data-type to VARCHAR and make its length to 20. Next is email, VARCHAR and 30. Next is password, VARCHAR and 32. Next one is role and last one is is_active. So, role is going to be‘tinyint’ and we need to store only one integer here. Like maybe we can store 1 for admin and 2 for author and 3 for maybe other type of users. So, let’s just keep its length to 1only. Is_active is there just to indicate three types of user’s authorization, like maybe we can have 1 for ‘pending users’, 2 for active and 3 for rejected maybe. So, let’s just keep it to tinyint as well and length only 1 character as well. We can also define Default values for both of them, when new record is inserted. So, let’s keep the role to 1 and this will be the author role, and 1 for is_active column as well and we are going to consider this 1 for user awaiting for approval. So, what does it means, this setting will make any registrant an Author and Awaiting for approval by default. We can also write comments for each of the columns to remember what was happening and why. Let’s comment this role column and write ‘1 for authors 2 for admins’ and let’s write comment for this is_active column as well, ‘1 for pending, 2 for active’. So, this will give us exact scenario we have set here when we will start coding relating these columns. So, we are almost done with this ‘users’ table, let’s save it. Here you can see now we have one table in our ‘crud’ database and that is users.

As we are going to create an articles site, so we need to store articles and article related data. So, we need another table here that will store all such kind of information. Let’s name this new table articles and keep 6 columns in it and hit enter from your keyboard or click this ‘Go’ button here. Now we need to define names and structure for each column of this articles table. So, first column is going to be the main identifier of this table so name it as ‘artID’ and type of ‘INT’ and let’s make it ‘primary’ as well as ‘auto increment’. Next column would be the ‘userID’ of type ‘INT’. This columns represents the ‘userID’ Primary field of ‘users’ table. So, this column will hold the ID of the user, who will submit the article. So, this is basically here to create a relationship between ‘articles’ and ‘users’ table. Let’s write a comment for this field to avoid any confusion. ‘Primary key of users table’. Next we need to store the name of articles that will provide reference to author when he would like to see all of his articles and would be able to guess each article separately. Let’s name it ‘art_name’ of type ‘VARCHAR’ and make its length 50 characters. Next we need to store title of the article that we will show at the start of each article as main heading or title. So, let’s name it as ‘title’ of type ‘VARCHAR’ and of length 100 characters. Next we want to store the content of the article, so, name it ‘content’ of type ‘MEDIUMTEXT’ as there can be a lot of text. Lastly, we need to store the date on which the article was uploaded or created. So, name it as ‘uploaded_on’ and type of ‘Date’ for now and that’s it. Let’s save this table, click ‘Save’ and now we have two tables in our ‘crud’ database, ‘users’ and ‘articles’.

We missed one thing in users table and that is we need to store the date on which user was registered. Let’s create this column now. Click ‘users’ table and inside here click ‘Structure’ and below here we have the option to add one more column. We can add this column at the end of the table, at the beginning of the table or we can select any field after which we would like to place this column. So, let’s click ‘Go’. Now we need to define structure and name of this field. Let’s name it ‘joined’ and set type to ‘TIMESTAMP’ and set a default value that is ‘CURRENT_TIMESTAMP’ for this column. This will automatically keep on adding timestamp for each new record. Click ‘Save’. Click ‘Structure’ and we have our new ‘joined’ field at the end of ‘users’ table. Now we have created the database ‘crud’ and two tables ‘users’ and ‘articles’ inside it, that are sufficient to store all the data of our site.



Connection File:

Now we have our database created. We need a PHP file that will help us making connection to mySQL and select the database that is ‘crud’. So, here we are going to create a separate conncetion file. This file will help us connecting promptly to DB whenever and wherever we need, just by ‘requiring’ it. Let’s create a new PHP file and name it connection. Let’s write ‘mysql_connect’ to connect to MySQL and between parentheses we need to provide, ‘127.0.0.1’ and ‘root’ and password is empty so leave this empty here too. Also, put the other stuff that will tell us about the error as well as kill the application. ‘or die mysql_error ’ and concatenate it with a custom error message ‘Could not connect to MySql’. This script will make the connection to MySQL, let’s now select our database, ‘mysql_select_db’ and give the name of our data base ‘crud’ between parenthesis and for link identifier let’s enclose our connection command in a variable $con and write it here as link identifier. For error handling just copy rest of the code from above here and paste it in here and that’s all. Let’s go to the browser to check if it’s working fine. Give exact path to the connection file and we get no errors. So, this file has been written correctly. This is our connection file ready to be included.

 

User Registration Continues:

Now let’s get back to the user registration code we were working on. Here we are checking if no any error was stored in errors array, means if there was no objection on the form submitted, only then we will register this user and store the information in DB. So, we will write this whole functionality here within this if statement.

Let’s first require ‘conncetion.php’ file at the top of this file. ‘require_once’ and put the name of the file ‘connection.php’. Now we can write MySQL queries here on this page. So, let’s start a query, ‘mysql_query’ and then parenthesis and rest of all stuff to handle the errors, if any. Now between double quotes, let’s write “INSERT INTO users ()” here we need to write the names of the columns in which we want to insert data. Let’s go to phpMyAdmin and then to our database ‘crud’ and in this we need to go to ‘users’ table and then structure and here we can view all the names of fields we need to insert data for. Let’s get back to code and put field names, ‘name’, ‘username’, ‘email’, ‘password’ and these are the only fields we need to supply data for as you can see in table that, ‘userID’, ‘role’, ‘is_active’ and ‘joined’ fields will be filled automatically. So, let’s remove this extra comma from here. Let’s format this code a bit for better readability. Write the keyword ‘VALUES’ here and then parenthesis and in here we need to supply values or data for these fields. This data is that we are receiving from the user’s submitted form in this code. Let’s put $name, $username, $email and $password and each of these within single quotes as the type for each of these is ‘VARCHAR’. Now let’s put this whole query execution in a variable and write an if statement and if this query executes put $qr here, only then we will echo the message to the user, ‘You have been registered successfully. Admin will authenticate you soon!’. If the querey doesn’t execute successfully then we will echo ‘Some internal error Please try again later!’ This is all, this code should work perfectly fine as far as user’s registration. Let’s verify it’s functionality by trying to register a dummy user.Let’s go to the registration.php page in the browser and put some dummy data for all the fields correctly and ‘agree to terms of service’ by checking the checkboxand click ‘register’ and there we go ‘success message’ it means no error was occurred and code is working perfectly fine. Let’s verify this from ‘users’ table. One record, we just registered with, has been inserted successfully. So, this is all for registration functionality.



Login Functionality:

Now we are going to develop the login functionality for all of our registered users either admin or author. So, let’s start working in login.php file. Let’s copy this registration form from registration.php page. Just put a heading ‘Login’ and paste the whole form here. Now we need only ‘username’ and ‘password’ fields here and ‘submit’. Let’s just change the value to ‘login’ and name to ‘login’ as well. Now we need to process this login form when submitted. So, here within these PHP tags, we will check if the form has been submitted then we will process further and then we will perform all the functionality on these two fields as we did for registration process. Let’s copy this whole functionality from registration.php page and copy in this login.php file. Now we can remove unnecessary field processing from here. Let’s remove this ‘name’ process, ‘email’,‘password’ and ‘terms’ as we don’t have these in our login form. If we don’t remove these we’ll definitely get errors.

In this ‘if’ condition, just remove all of this and here we will put the login functionality and let’s just remove this if else that is following the query execution. So, here if the form has been submitted correctly we will get 0 count from errors array and only then this execution area will work. So, here we need to check and verify the username and password given by the visitor.

Now let’s write a query which will match the credentials supplied by the user with the stored credentials. If these will match, we shall login this user otherwise we will show the error message. As we need to work with sanitize function as well as we want to run the query for database let’s require all the files we need. So, require_once, the sanitize file as well as require_once the ‘connection’ file.

Now let’s complete the query, ‘Select’ and we need two things here ‘username’ and ‘password’ ‘From users WHERE username = ‘$username’ and password = ‘$password’’ and let’s just enclose both of these within single quotes as both of these have type ‘VARCHAR’. Let’s put this query in a variable ‘$qr’. Here let’s use a mysql function ‘mysql_num_rows’.This function counts and returns how many records were found as result of query we supplied it. So, if the result of this function is greater than 0, then obviously it means the credentials ‘username’ and ‘password’ supplied by the user matchedwith one of the stored record. So, if this happens, we will log this user in otherwise we’ll show the error message. So, let’s put this line of code with in an ‘if’ statement and if this happens, right now we will just show the message, ‘Logged in’ otherwise we’ll show the message ‘Invalid login credentials.’ This is just to check that everything is working fine. So, let’s go to the login.php page in browser and give the credentials of our stored user, click login and it’s displaying us an error. Let’s check this out what the problem is and off-course we putan extra ‘s’ here. Remove it and back to browser again and give the right credentials and ‘Logged in’ message. Now, let’s give the wrong credentials and we get ‘Invalid login credentials’ message. Now if we leave any of the fields empty we need to show the error message right above the form. Let’s create the same functionality we created in registration.php file. ‘if’ errors array has count value and greater than 0 only then we will run a ‘foreach’ loop on $errors array and will get each value as $error variable and finally let’s just echo ‘$error’ and just put a ‘br’ tag at the end of each error. Let’s now check this functionality in browser, put a dummy usernameand leave the password field empty, click login button and it shows us the error message. Let’s remove username and supply password and it again shows us error message.

Now here at this point we will create the login functionality and will redirect our logged in user to control panel main page that is our index.php. We can use header function here and within double quotes we’ll give location and the exact path to the file index.php.

In the index.php just to differentiate it from other pages let’s give a heading, ‘welcome to control panel’. Now let’s get back to the browser and give the correct credentials and here we go, you can see we have been sent to the index.php page and you can see the welcome message here. This is how we redirect our users from one page to another depending on their credentials. Now let’s go to the ‘crud’ database and to our ‘users’ table and here we have a field which was to keep users pending or active. When this field will have 1 for a record, that user will not be able to login and will not have access to his control panel. Only the user having 2 in this field will be redirected to his control panel. So, let’s append our code a bit to get this functionality. So, we need to check in our query here ‘AND is_active = 2’ So, this is all, this is the only thing we need to append in the query. So, this query will select only that record where ‘username’ and ‘password’ match the recorded credentials as well as ‘is_active’ = ‘2’. Rest of all is same. Now let’s go back to the browser and on this login page put the correct credentials that are stored in DB, but you can see when we click login it’s showing us message of invalid credentials.

Now, let’s go to the ‘users’ table again and let’s make this 2, that we will use for active users or to activate users. Now this user must be redirected to his control panel. Let’s go to the login page and give the correct credentials again, and this time you can see the user has been redirected to the Control Panel.


Working with SESSIONS:

Now, let’s have a look at a scenario. Let’s just paste the control panel URL that is index.php in another tab and hit enter and you can see it’s accessible without being logged in. So, we need to restrict the access on the control panel without being logged in. So, here we need to work with sessions. Let’s start session here and generate a session that will hold the any state active. As you know we have two types of users, author and admin. So, to create a new session here we need to know what is the role of this particular user that wants to login. For this we need to select role from ‘users’ table. So, let’s write role here and we also now have to get this data out of this query to use it. So, just use ‘mysql_fetch_assoc’ function and supply$qr that is our select query to it. Just store this result in a variable $row. Now just get the value of role from this $row associative array. Put this in a variable $role. Now let’s have a look at ‘users’ table and here we will have only 1 or 2. If it’s 1 the user will be author and if its 2 user will be admin. Let’s get back to the code and we can place this variable $role instead of this one here and this will assign the value 1 or 2 automatically from DB. We can name this session ‘role’ and that’s it. So, now the session will be generated only if the user’s provided credentials match the recorded credentials and the field is_active is set to 2. This role session will contain the value 1 or 2 from it’s concerned record. Then we shall use this session to restrict and permit this particular user to access on different areas of the website. So, to understand it simply you can think of this as 2 or maybe 1.

Now to develop permission scenario on index.php that is the control panel main page, let’s declare an ‘if’ statement here. So, if the session ‘role’ is not set, and off-course we need to start session at the top of any code, so, if the ‘role’ session is not set then redirect this user to the login page and don’t let this user even visit this control panel. So, what we have done here is, if in any case ‘role’ session was not created, that we are generating only if the user has correct credentials and active, the user will be redirected back to login page. So, this is all we need to restrict any user to visit this page who has not been logged in.

Let’s get back to the browser and here we are in control panel, just refresh this page and you can see we have been sent out from control panel back to login page, because at the moment no session variable has been registered. Now let’s try to login using correct credentials. Click Login and here we have an error. OK there is a spelling mistake, let’s just correct it and try to login one more time, just refresh it and we are in Control Panel as now the session variable has been registered.



Create Menu Links:

Now you can see our pages are increasing and to move between pages we need to have links. So, let’s create a separate links file to have all those links and we can then easily include or require this file on all the pages we need. So, name it as links.php. At the moment we just need HTML links on this file, so let’s erase PHP tags from this page and create an anchor tag and give the hyper reference ‘index.php’ that is the main page and just name this link as ‘Control Panel’. Let’s create another link and this is for our ‘login.php’ page and just mention Login for the link text. Another link tag and put ‘logout.php’ as anchor and this is the file we will create in a moment and write the text for this link as ‘Logout’. Another link and this is for our ‘registration.php’ page and give it the text ‘Registration’. Let’s just bring it near to login link and just place spaces between these links using ‘&nbsp’ and this is all for links file. Let’s first include this file in ‘registration.php’ and just above the start of the content of this page, we need to display links here. So, let use ‘include_once’ internal function and then ‘links.php’ within single or double quotes, include it in ‘login.php’ and in ‘index.php’ as well. Now let’s get back to the browser to view these links in action.You can see that all the pages are working in connect to our links. So, all the links have been included easily on all the pages. So, whenever, we need to change something regarding links, we will just go to our links.php file and can do the necessary changes. Now, this is Logout link that is taking us to ‘logout.php’ page that we have not created yet, as you can see its giving us an error. Let’s create it now.

Logout Page:

Let’s right click here and create new PHP file and name it as ‘logout’. This is our logout file. So, this file is going to help us just removing or destroying the sessions to log out any particular logged in user when he clicks on this logout link. So, first thing we need is to start session here on this file so that we can work with sessions. Now, just write an internal function ‘session_unset’.This internal function unsets any session that has been already set. This is all for removing any session and will logout the user, but we then want our user to move on login page automatically. So, right after this we can call the header function and set the location, ‘login.php’. So, this logout file will remove all the sessions and take the user to login.php page. Let’s now verify this functionality in the browser. Just click the ‘logout’ link and we are sent to login page. Now just try to go back to control panel, click this link but it’s not taking us to Control Panel. So, our logout page is working perfectly fine.

Now, let’s login one more time with correct username and password and we are in Control Panel, let’s check all the links, registration, login and then try to go back to control panel again and we are able to get back to control panel, as our session is still set. Click logout link again and we are at ‘login’ page. Now if we try to access Control Panel it’s not possible as our session has been terminated. Now, let’s go to the index.php and here you can see we have coded that if the $_Session[‘role’] is not set than take this user to login.php page. This is all for logout.php page.

This is it for the Day 14. We have developed much of the functionality of the backend. But still few of the backend and most of the frontend functionality remains that we will definitely going to cover on day 15. See you on day 15.



Related Posts:

Leave a reply

Required fields are marked *

Login to Post Comment