Creating Your First PHP Application: Part 3

Creating Your First PHP Application: Part 3

In part 1 and part 2 we built the necessary classes, created a database table for our users and made a global.inc.php file that will act as a bootstrap on every page.

What’s Next

We’re now ready to build the front end pages. Bear in mind that everything you see here can be expanded and improved upon. For the purposes of this tutorial I’ve kept things relatively simple. For some suggested improvements, check out the “Extra Credit” section at the end of the post.

User Registration Page (register.php)

There are two parts to this page. A block of PHP at the top and the HTML at the bottom. As you develop your website, you may find that you’ll organize the code differently, but for clarity’s sake I kept it simple for this tutorial.

The PHP at the top loads the bootstrap (global.inc.php). It also contains the code that will be used for the form validation. The HTML at the bottom contains a simple registration form. A more detailed explanation can be found following the code.

The Code

What It’s Doing

The HTML portion of the code should be relatively straight forward. The form action is set to register.php with the method being post. This means that when the form is submitted, register.php will be loaded again and the values in the fields will be sent in the $_POST variable.

The value of each input field is set to a PHP variable ($username, $password, etc). If the form hasn’t yet been submitted, all the values will be an empty string. If the form has been submitted and did not validate, those variables will contain the values from the previous submission of the form so that they do not need to be filled in again.

Additionally, if the form has been submitted and did not validate with the PHP code above, then the $error variable will be displayed. This variable will contain the reasons why the form did not validate.

The form validation is fairly straightforward as well. The $_POST variable is an associative array of variables passed to the current script via the HTTP POST method. Each form field’s value can be accessed in $_POST by using the name of the field as the key. The first thing we do is check to see if the submit button has been press (i.e. the form has been submitted). We check $_POST['submit-form'] with the isset() PHP function since “submit-form” was the name of the submission button on the form.

Once we know the form has been submitted, we can validate it. We’ll be using the UserTools class we created in part 2 to check to see if someone has already chosen the submitted username. If so we’ll flag the form as unvalidated by setting $success to false and we’ll describe the error in $error. The next step is to check to see if the passwords match using a simple comparison.

If the form validation was successful, we’ll put the information in an associative arrray called $data and use that array to create a new User object. We’ll they call the save() function of that User object with the $isNewUser flag set to true. We then log them in using our login() function (found in the UserTools class) and redirect them to welcome.php.

Here is some example code you might use for welcome.php:

Login and Logout Pages

login.php

Much like register.php, login.php will have form validation at the top and the HTML login form at the bottom. The form is just two fields, username and password. The form validation calls the UserTools login() function and redirects them to index.php if login() returns true and displays an error if login() returns false. Very simple and easy. Here’s the code:

logout.php

Logging a user out is even simpler than logging them in. This page needs no HTML. It just logs them out using the logout() function we put in the UserTools class and redirects them back to index.php. Here’s the code:

User Settings Page

A registered user that is logged in may want to change their settings. To keep this example simple, we’re only going to allow them to change their email address. You may want to try and expand this to enable a user to change their password.

Much like our register.php and login.php pages, there will be an HTML section with the form and a PHP section containing the form validation and other vital PHP operations. In this case, when the form is submitted we’ll get the current user as a User object from their session and set the email attribute equal to the new email. We then simple call the save() function in the User class and the desired result is achieved.

The Code

The Final File – index.php

With index.php, the sky is the limit. Since this tutorial was mostly about setting up a very “bare-bones” app, I’ll leave this mostly to your creativity. To get you started, here’s some basic code that shows links to “login” or “register” if the user is logged out and shows links to “logout” or “change settings” if the user is logged in.

Extra Credit / Taking it Further

Because this tutorial is admittedly basic I’ve come up with a list of thing you may want to improve upon on your own.

  • Error handling in each of the classes
  • Protection against malicious form submissions and sql injection
  • Implementing the PHP singleton pattern for the DB class
  • Use include() to build a template
  • Add a “remember me” check box that utilizes cookies to keep the user logged in
  • Configure include_path in php.ini or with ini_set() for easier inclusion of files in different directories

Further Reading

As you become more familiar with OOP and PHP, here are some suggestions for developing quality applications:

Final Words

I hope you’ve enjoyed this tutorial. A zipped folder of the entire project is available for your downloading pleasure. Simply set up your database, configure DB.class.php with your database settings, and put the contents of the zip in your root folder.

Posted Monday, December 14th, 2009 · Back to Top

SPONSOR

Add Comment

45 Comments 1 Mentions

  1. Nick Parsons Author Editor

    This has been an excellent set of tutorials, Brian! Although it is real basic (like you said), you did a great job putting together a good, clear explananation to get someone started.

    I like the fact that you walked through all the organization and setup, not just the actual coding like a lot of tuts do. Great work!

    ·

  2. Destiny Islands Author Editor

    There are so many great PHP tutorials out there on the web, it’s almost impossible not to understand PHP by now as a web developer!

    ·

  3. Rockstyle Author Editor

    Great tutorial, looking forward to see more. Would be nice if you made some series about theming (theming like in wordpress – files) clean html instead of echoing, this would be really great. I actually don’t see download link to get all the project files, could you fix this?

    ·

  4. Sérgio Soares Author Editor

    Nice tutorial. Awesome series.
    Could u add the source code, i’m having problems with my application on login step.
    thanks

    ·

  5. Austin Author Editor

    Oh, there we go. The singleton pattern is what I was looking for. I understand things now. :)

    Pretty much disregard my comment on the last post. Thanks, and great tutorials!

    ·

  6. Zach Dunn Author Editor

    I’ve updated the post to include source files. You can also download them through this link.

    ·

  7. Shrinivas Author Editor

    Well written and explained article, I’m pointing guys looking to begin with php+mysql to this set of tutorials. Thanks!

    ·

  8. Brandon Author Editor

    Thank you for the tutorials. I am new to OOP and php classes.

    Question: Why would the error handling to be inside the UserTools class?

    Thanks for your help.

    ·

  9. Brandon Author Editor

    Correction to my question:

    Why would the error handling not be inside the UserTools class?

    Thanks again!!

    ·

  10. nightmare Author Editor

    The installation process I encountered this error:
    http://hitupload.net/files/errorphp.jpg
    Please help !!

    ·

  11. thorkon Author Editor

    I get an error “unserialize() expects parameter 1 to be string, object given in includes/global.inc.php on line 20″.

    How can I get rid of it / what’s wrong?

    ·

  12. Zack Author Editor

    I’ve got the same error as thorkon. And two more error later:

    Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\AppServ\www\cms\classes\DB.class.php on line 42

    Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in C:\AppServ\www\cms\classes\DB.class.php on line 25

    ·

  13. Zack Author Editor

    I found that, after login, page redirects to index.php, after the unserialize was run, all the SESSION settings($_SESSION['user'], $_SESSION['logged_in'], $_SESSION['login_time']) will change to numbers, so that if you run change email page, or logout, the unserialize() function gets error.

    But I am not sure what causes this, is it about the unserialize() function?

    ·

  14. Tao Author Editor

    I had the same problem and solved it by putting an “php.ini” file on the app folder (together with the front end files) containing only “register_globals = off”.

    (thanks Brian Muse for your assistance!)

    ·

  15. Brian Muse Author Editor

    @Tao and others
    Register globals is most likely your problem, as Tao pointed out. This ini directive was turned on by default for versions of PHP below 4.2. Since 4.2.0 it has been turned off by default and using it is highly discouraged.

    In fact, it is being completely removed in PHP 6.0.

    Learn more here: http://www.php.net/manual/en/ini.core.php#ini.register-globals

    ·

  16. yoenk Author Editor

    Thank you for the great tutorials.i want to display all user .so i create a method like this below,

    public function displayAllUser() {
    ……………………
    }

    but could you give example what should i fill in that method …. please ???

    ·

  17. Alejandro Author Editor

    In the script I add the validation set common to display “user input”, “enter password”, “enter email” and apart to check if the entered email exists.
    Greetings!

    ·

  18. dreb Author Editor

    I completed the tutorial for one overnight. It was great and the codes were presented in a very presentable way.

    Many thanks guys for sharing this one. Looking forward for another web applications.

    More power!

    ·

  19. adam Author Editor

    thanks for this great tutorials
    :)

    ·

  20. Onkar Kubal Author Editor

    Nice Tutorial.Ideal for new bees like me

    OnCar

    ·

  21. Shahnawaz Baghdadi Author Editor

    Good tutorial

    ·

  22. will Author Editor

    if i put a check box in this code how do i define it ??

    ·

  23. Software Author Editor

    This Tutorial is very helpful for beginners, Thanks for sharing!

    ·

  24. adity Author Editor

    nice tutorial dude,

    ·

  25. hoewel het reizen Author Editor

    I was extremely pleased to discover this particular web-site.I wanted to thank you for your precious time with this great study!! I ACTUALLY definitely taking advantage of any little it all and I had you saved to check out latest stuff you blog post.

    ·

  26. Cheap Louis Vuitton Epi Leather Eugenie Ivory M6388J Author Editor

    It is perfect time to make some plans for the future and it’s time to be happy. I have read this post and if I could I desire to suggest you some interesting things or advice. Maybe you could write next articles referring to this article. I wish to read even more things about it!

    ·

  27. Dog Author Editor

    I have been meaning to write about something like this on my webpage and this has given me an idea. Thank you.

    ·

  28. Cheap Monster – Beats By Dr Dre Studio LeBron James – Gold Author Editor

    I have been surfing online more than 3 hours today, yet I never found any interesting article like yours. It’s pretty worth enough for me. Personally, if all web owners and bloggers made good content as you did, the internet will be much more useful than ever before.

    ·

  29. Inspirational Quotes Author Editor

    Creating Your First PHP Application: Part 3 | Build Internet I was suggested this website by my cousin. I’m not sure whether this post is written by him as no one else know such detailed about my difficulty. You’re incredible! Thanks! your article about Creating Your First PHP Application: Part 3 | Build Internet Best Regards Cindy Yoder

    ·

  30. Inspirational Quotes Author Editor

    Creating Your First PHP Application: Part 3 | Build Internet I was suggested this website by my cousin. I am not sure whether this post is written by him as nobody else know such detailed about my trouble. You are incredible! Thanks! your article about Creating Your First PHP Application: Part 3 | Build Internet Best Regards Cindy Shane

    ·

  31. Bilety Lotnicze Author Editor

    I always was concerned in this subject and still am, regards for posting.

    ·

  32. vamshi Author Editor

    Realy realy fantastic tut for startup’s… keep rocking man.. al d best..

    ·

  33. Mike Author Editor

    Hi!
    I’ve found this tutorial very interesting. Thank you for sharing, it works great!

    A simple question: Is there a way to add the checkbox “Keep me logged in”?

    Thanks again.

    ·

  34. Kristy Author Editor

    Excuse me

    There is one warning appeared when I run register.php
    Warning: Cannot modify header information – headers already sent by (output started at C:\AppServ\www\classes\DB.class.php:93) in C:\AppServ\www\register.php on line 57

    I think the error in this line
    56 //redirect them to a welcome page
    57 header(“Location: welcome.php”);

    ·

  35. loureMolI Author Editor

    [url=http://kreditnijbank.ru/] Взять кредит в ФИЛИАЛ ООО КБ НАРАТБАНК В Г.ЭНГЕЛЬСЕ [/url] ? Теперь это не проблема! Любой кредит под маленький процент ждет тебя!

    ·

  36. Shailendra Author Editor

    Just one word…awesome :)

    ·

  37. Daniel Author Editor

    Nice tutorial!

    As a beginner in OOP I have trouble deciding which methods should belong to which class. In my unexperienced mind it would feel logical to skip the UserTools and just expand the User class to include all the methods related to users.

    Could someone please explain the benefits of having a separate UserTools class?
    And the logic behind checkUsernameExists belonging to UserTools but save belonging to User?

    ·

  38. sagun Author Editor

    really really a great tutorial….. the reusability is clearly exposed..

    ·

  39. JP Author Editor

    Very nice tutorial. This really helps me understand some things I wasnt getting. BTW the download link for the tutorial files is at the top left under the author’s photo,for those that couldn’t find it..

    ·

  40. Babatunde Quadre Author Editor

    this tutorial is the best tutorial i have come across on learning OOP PHP as a beginner bravo.

    ·

  41. shiv Author Editor

    Super!

    ·

  42. jimmy Author Editor

    Hi there, where are the zip files that you mentioned?

    ·

  43. sixli Author Editor

    Thanks for the awesome tutorial!

    I have a problem I can’t sort out – Warning: mysqli_query() expects at least 2 parameters, 1 given in [location]\classes\UserTools.class.php on line 39
    which is the checkUsernameExists query: $result = mysqli_query(“SELECT id FROM users WHERE username = ‘$username’”);

    Can you please, advise?

    Thanks!

    ·

  44. Judith Author Editor

    Hi, I wish for to subscribe for this weblog to take most up-to-date
    updates, thus where can i do it please help out.

    ·

  45. Знакомства без обязательств Author Editor

    An outstanding share! I have just forwarded this onto a coworker who had been doing a
    little research on this. And he actually ordered me breakfast due to the fact that I found it for him.
    .. lol. So allow me to reword this…. Thank YOU for the meal!
    ! But yeah, thanx for spending some time to discuss this issue here on your web page.

    ·

 

Build Internet by One Mighty Roar. Since 2008.