Creating Your First PHP Application: Part 2

Creating Your First PHP Application: Part 2

This post is the second part in a three part series covering how to build a basic web application using OOP PHP. In part 1 I discussed the folder structure, the goals of the project and we created our first class called DB.class.php (a class to handle our common database operations).

In part 2, we’ll be writing two more classes and we’ll be finishing up the “back-end” portion of this basic web application.

The Plan

The ultimate goal of this project is to create a basic application that allows a user to register, log in, log out, and alter their settings. The class we will use to define what a user is and retain all of their user information will be called User and will be defined in User.class.php. The class that we will use to handle user operations such as logging in and out will be called UserTools and will be contained in UserTools.class.php.

A note about naming conventions

Although it does not matter syntactically, it is a common practice to name the file containing the class with the same name as the class itself. This makes it easy to identify the purpose of each file in your classes folder.

Another common practice (that has nothing to do with code execution but can be helpful) is the addition of .class or .inc in the file name. This better defines what the file is and also allows you to more easily restrict public access to certain files in your .htaccess file if you’re using Apache. It is still best practice to have every file end in .php despite the ability to set your webserver to parse PHP in files with .class and .inc extensions.

The User Class (User.class.php)

This class will be defining exactly what a user is. You’ll find that as you expand your web application, your definition of a User may also broaden. Luckily the OOP approach to web development allows for more user attributes to be easily added.

The Constructor

We’ll be using a constructor in this class, which is a function that is called automatically every time a new instance of the class is created. This essentially allows us to automatically populate certain attributes upon creation of the object. In this class, the constructor will take a single argument: an associative array containing data from a single row from the users table in the database. An alternative way to do this could be to use the user’s unique id as the argument and do the database operations from within the constructor. It’s merely a matter of preference as your design your web application.

The Code (with explanation following)

Explanation

The first bit of code in the file is outside the class ensures that the DB class has been included, since the User class has a function that requires it.

As for the class definition itself, you should see some similarities to the DB class that we created in part 1. Instead of the class variables being defined as “protected”, we’re defining them here as “public”. This means that any code outside of the class has access to these variables when dealing with a User object.

The constructor is takes an associative array, where keys are columns in the users table. We set a class variable by using $this->variablename. In the case of this class, we first check to see if a value for a particular key is set. If so, we’ll set the class variable equal that that value. Otherwise we’ll set it to an empty string. The code uses the short form for an if statement as detailed below:

It tests to see if 3 is equal to four. If it is, $value = “A”. If not, $value = “B”. In this case, $value will be set to “B”.

Saving the User’s Data to the Database

The save function is used to update the users table in the database with the current values in the User object. This function utilizes the DB class we made in part 1. Using the class variables, an associative array called $data is set. If the user is being saved for the first time, $isNewUser should be passed in as $true (default is false). If $isNewUser is equal to true, then the insert() function of the DB class is called. Otherwise, the update function is called. In both cases, the data from the user object will be saved to the database.

The UserTools Class (UserTools.class.php)

The UserTools class will contain functions relating to users. Although you may find yourself adding to this class as you customize and expand this project further, we’ll just be dealing with four functions: login(), logout(), checkUsernameExists() and get().

The Code (with explanation following)

The login() function

The login function serves an obvious purpose. Taking the $username and $password of the user as arguments, this function verifies their credentials. If the username and password match, we’ll create a User object with all their information and store the object in a session. Notice we’re first using the PHP serialize() function. This generates a storeable version of the object and can be simply undone by calling unserialize(). For good measure it will also store the login time. This can be used later on to tell the user how long they’ve been logged in for or to expire the session manually after a certain period of time.

You’ll notice that we’re also setting $_SESSION['logged_in'] to 1. This provides us with an easy way on every page to verify if the user is logged in or not. Simply check to see if that variable is set.

The logout() function

This function is fairly self-explanatory. The PHP unset() function clears the variables in memory while session_destroy() will delete the session altogether from storage. Why not skip using unset() and just use session_destroy()? It’s mostly for completeness sake and a matter of personal preference. You could also use $_SESSION = array() instead of unset() for each separate value. I prefer listing them all individually so that the code is readable and we can see exactly what session variables are being used and cleared.

The checkUsernameExists() function

Side note: Notice that in all cases, the function name clearly describes exactly what the function will be doing. This is probably the best example of that and in general you should try to continue clearly naming both functions, classes, and variables in your code.

This function simply queries the database to check whether a particular user name already exists. If it does, it will return true, otherwise false.

The get() function

This function takes a unique user id and queries the database using the DB class’s select() function. It will take the associative array returned by the select() function containing the user row and pass create and new User object, passing that array into the constructor. This User object is then returned.

Where might you use this? Lots of places. For example if you create a page that displays users public profiles, you’ll need to dynamically grab their information and display it. Here’s how you might do that: (let’s say the URL is http://www.website.com/profile.php?userID=3)

Isn’t that simple?

The final piece of the backend: global.inc.php

The file global.inc.php will be required by every page on the website. Why? This way we’ll have a place to put common operations that we’ll need on every page. For example, it will call session_start(). It will also open a database connection.

The Code

What’s it doing?

There’s a couple different things going on here. Firstly, we’re opening up a database connection. This was outlined in part 1, and here’s where we’ll actually be using it.

Once we’ve connected to the database, we call the PHP function session_start(). This function creates a session or resumes the current one if the user is logged in. Because our web application has users logging in an out, this is absolutely mandatory on all pages. By putting it in global.inc.php we can assure that it will always be called.

The third thing we’re doing is checking to see if they’re logged in. If they are, we’re going to refresh $_SESSION['user'] so that it reflects the most current data we have for that user. For example, if a user changes a setting like their email address, the session will still have the old email address. This ensure that the session will always be up-to-date.

Extra Credit

Try expanding the User class and your database table to include more attributes. For example you might try adding birthday, address or personal website as attributes.

One thing that I’ve omitted in this tutorial that you’ll want to add in later is error handling. The ultimate goal should be to never have something unexpected returned by a function. One place you can attempt this is in the get() function in UserTools.class.php for when a user id is passed to the function that doesn’t exist in the database.

Try making your own function in UserTools.class.php. An example might be a function to get all users that registered after a certain date and return them in an array of User objects.

What’s up next?

This concludes part 2. We’ve managed to build the rest of our back-end for this basic web application. But in order to bring everything together we still need to build all of the front ends. Here’s what you can expect in part 3:

  • Front end PHP/html pages that utilize our back-end
  • Forms and form handling (registration page, login page, update settings page, etc)
  • More on displaying session data and building a dynamic page

Posted Wednesday, December 9th, 2009 · Back to Top

SPONSOR

Add Comment

34 Comments 4 Mentions

  1. Mr.MoOx Author Editor

    It ‘s a nice tutorial for beginner.
    Do you know the Zend Framework for PHP ? It’s a full oriented object framework wich provide a lot of tools.
    Supported by the PHP Company (Zend!), you can use it for make strong php application. Here is a quick start : http://framework.zend.com/docs/quickstart
    I’m not from the Zend Company, I just really like this framework !

    ·

  2. Brian Muse Author Editor

    @Mr.MoOx
    These tutorials are designed for those who are just getting into PHP and would like to know more about basic OOP.

    Both the Zend and Codeigniter frameworks are excellent tools for people to become familiar with once they’ve mastered the basics. (In fact, our project at http://yourather.com is built using the Zend Framework)

    If there’s a demand for it, I could do some Zend Framework and Codeigniter tutorials in the future.

    ·

    • Emmanuel Author Editor

      Hi Brian! Really great tutorial. Well structured, easy to understand and relevant.

      I wonder why the UserTools class methods “login” and “checkUsername” don’t use the DB class? Is there any grand idea behind that?

      ·

    • Rohith Author Editor

      Brian Muse, thanks for a great tutorial, can you please do a zend framework beginner tutorial?

      ·

  3. Michal Majer Author Editor

    Great tut, canť wait for the next one .. just one question .. How am I supposed to remember all the classes and what they do at all time, when I’m developing new project? :) Even in this simple tut, the third class uses object of the second class and the second uses object of the first class .. I had some troubles scrolling the page just to find out what the class is actually doing =P

    ·

  4. Carlos Author Editor

    Codeigniter tutorials would be awesome…

    ·

    • Fantine Author Editor

      Oh yeah, fabuuols stuff there you!

      ·

  5. Sérgio Soares Author Editor

    Nice tutorials!
    I’ll follow this series for sure.

    Thanks

    ·

  6. jyoseph Author Editor

    As a Coldfusion developer who has only dabbled in php, these tutorials really help everything come together.

    Surely this will help people to move from “just hacking at php” to being able to put an actual web app together.

    Many thanks, please keep up the good work!

    ·

  7. Prospect Solution Author Editor

    Awesome..I must study now php and build my own website.

    Is there a part 3 until a complete website? lol

    ·

  8. Austin Author Editor

    Great tutorial, but it seems kind of redundant to initialize the database class every time that the save function is called. I’m not an OOP expert and I barely use OOP, so I don’t know exactly how I would approach it. I would probably use a global variable and then use global $db; to access it from each individual methods. Or something like that.

    ·

  9. GaryT Author Editor

    I must say that PHP scared me at the beginning but now, everything seems so easy!

    ·

  10. MediaTech Author Editor

    This is brilliant, thx! Saved me alot of time and I know where to start at least :)

    Thanks again!

    ·

  11. Jernej Author Editor

    Great stuff, thx!

    One question though. Why is it neceseary to refresh the user data in global.inc.php:
    $_SESSION['user'] = serialize($userTools->get($user->id));

    My login was causing me problems ( the values were always empty ), but once I removed the line above, everything is working fine.

    Was is some kinda safety percussion?

    ·

  12. Jernej Author Editor

    Nevermind the question above, I see you described it well in the article, not sure how I missed that :p

    ·

  13. Men web cams Author Editor

    We’ll be using a constructor in this class, which is a function that is called automatically every time a new instance of the class is created. This essentially allows us to automatically populate certain attributes upon creation of the object. In this class, the constructor will take a single argument: an associative array containing data from a single row from the users table in the database. An alternative way to do this could be to use the user’s unique id as the argument and do the database operations from within the constructor. It’s merely a matter of preference as your design your web application.

    ·

  14. bulletproof Author Editor

    Hello Great informative article! Thanks so much for sharing your wealth of information. I certainly appreciate the effort! keep up the good work!

    ·

  15. ProFlightSimulatorFree Author Editor

    Hello! This has been very helpful. some really good information and tips! Thanks for all of your hard work!

    ·

  16. forex morning trade Author Editor

    Hi! I found this article to be very interesting and greatly enjoyed reading it. Thanks for all of your hard work!

    ·

  17. news sites Author Editor

    Nice post. I like this page.

    ·

  18. San Diego cemetery Author Editor

    Great post,very informative.
    Please continue to write more
    interesting post in your blog.

    ·

  19. Marbo Aktivator Author Editor

    I’m happy to have found your really high-quality article! I agree with some of your readers and will eagerly look forward to your coming updates.

    ·

  20. Essay Writing Author Editor

    This is a great tutorial. Happy to have come across it. I build websites but I only use thrid party tools.

    ·

  21. pletcherbuj Author Editor

    I really believe [url=http://www.beatsdrdremart.com/monster-beats-studio-c-1.html]beats by dre studio[/url] Fantastic Justbeats Black characteristics a fantastic consider using this type of organized also. An absolute audiophile headset even usually not built with plenty of endorsing, are capable to caring for the intensive visiting team nowadays in this trade. As expected, with no sincere strength of mind as a way to customers’ prizes as well as the outstanding techies this type of can not be performed.

    Regardless of legitimate striper completed [url=http://www.beatsdrdremart.com/monster-beats-studio-studio-overear-c-1_2.html]studio dre beats[/url] while in the suitable tactic, feel is usually as thorough so that as correct considering that Huge Kilometers Davis Homage will offer you. As well as end result is very okay. Do you find it pricy? Simply were definitely shelling out $300 along with imagined tone cancellation, It’s safe to get the answer mainly because serene level of comfort. Shifting the particular power packs can be described as pain. No a person desires to suffer from the truth that during ones own fulfillment. Then again qualifing for the result of the actual down the road amusement relating to tracks, that you are with the worthwhile placement in any case.

    For [url=http://www.beatsdrdremart.com/monster-beats-pro-c-19.html]beats by dr dre pro[/url] fond of the particular cold style connected with being dressed in excellent sealed earbuds, Monster Surpasses See Zero Controltalk plays typically the mandate to be ideal for your final decision consequently well going without shoes finds out each of those of the aspects for your personal need. First we need to work out one reveal all the event this just how this ease and comfort is produced by.

    Anything [url=http://www.beatsdrdremart.com/monster-beats-tour-c-24.html]beats by dr dre tour[/url] affiliated Yao, that navigate huge, generally accompany thriller together with astonish, that include darkness about the 100 % pure excellent, creates individuals commitment. With regard to Monster Yao Ming, many people without doubt subsequently left most people shocked immediately after airline considering the soothing institution with him / her. Yet, everyone are actually a form of what person surely are actually tight and have absolutely getting some specific good notiion connected with fashion or a big trend better half. It’s unfullfiling to support state to you personally round the fashion issue. Regardless there does exist just headphone no longer up-to-date clothes.

    ·

  22. Erydridwize Author Editor

    домашнее видео проститутки
    проститутки мужчины киев
    проститутки киева дарницкий
    проститутки москвы очень дешево
    анкеты проституток киев

    прямоугольник, составила подробный список необходимой одежды, а также пояснила, где именно лежат требующие срочной оплаты счета. К счастью, и
    согласилась. Она значительно моложе меня и очень привлекательна. Я смотрела на отца с несчастным видом, надеясь, что все это просто шутка. Скажи
    углу комнаты с Мастерсом, показывавшим ему инструмент, которым они пользовались. Посмотри, какое у него острое лезвие. Это для того, чтобы резать.
    как покинула Англию, я поняла только то, что я знаю так мало. Я вышла на террасу. Шум гавани казался какимито отдаленным. Я села, мысли у меня
    привычным, что, казалось, его придумала сама природамать. В одном месте ширина канала достигала почти полмили. Блэквелл пытался найти знакомые

    [url=http://itiwodus.comuf.com/art.php?article=kupit-prostitutku]Купить проститутку[/url]
    [url=http://itiwodus.comuf.com/art.php?article=gde-snyat-tulskuy-prostitutku]Где снять тульскую проститутку[/url]
    [url=http://itiwodus.comuf.com/art.php?article=prostitutki-moskvi-marino]Проститутки москвы марьино[/url]
    [url=http://itiwodus.comuf.com/art.php?article=dasha-prostitutka]Даша проститутка[/url]
    [url=http://itiwodus.comuf.com/art.php?article=prostitutki-gorod-moskva-deshevie]Проститутки город москва дешевые[/url]

    [url=http://iveyitet.host22.com/art.php?article=dosug-chehov-prostitutki]Досуг чехов проститутки[/url]
    [url=http://iveyitet.host22.com/art.php?article=prostitutki-invalidki-pokazat-vse-anketi]Проститутки инвалидки показать все анкеты[/url]
    [url=http://iveyitet.host22.com/art.php?article=prostitutki-g-orenburgskaya-oblast]Проститутки г оренбургская область[/url]
    [url=http://iveyitet.host22.com/art.php?article=jena-bivshaya-prostitutka]Жена бывшая проститутка[/url]
    [url=http://iveyitet.host22.com/art.php?article=prostitutki-moskva-metro-sokol]Проститутки москва метро сокол[/url]

    [url=http://izavoza.host22.com/ctg.php?category=9&page=2]Оголяет проституток в gta iv[/url]
    [url=http://izavoza.host22.com/art.php?article=zakazat-prostitutku-v-n-novgorode]Заказать проститутку в н новгороде[/url]
    [url=http://izavoza.host22.com/art.php?article=prostitutki-individualki-minet-bez-prezervativa]Проститутки индивидуалки минет без презерватива[/url]
    [url=http://izavoza.host22.com/art.php?article=prastitutki-bryanska]Праститутки брянска[/url]
    [url=http://izavoza.host22.com/ctg.php?category=6&page=2]Темнокожие проститутки[/url]

    [url=http://izodege.host22.com/art.php?article=prostitutki-m-strogino]Проститутки м строгино[/url]
    [url=http://izodege.host22.com/ctg.php?category=10&page=1]Праститутки после сорока москва[/url]
    [url=http://izodege.host22.com/art.php?article=deshevie-prostitutki-tymeni]Дешевые проститутки тюмени[/url]
    [url=http://izodege.host22.com/art.php?article=prostitutki-g-angarsk-foto]Проститутки г ангарск фото[/url]
    [url=http://izodege.host22.com/art.php?article=prostitutki-moskvi-mama-s-dochkoy]Проститутки москвы мама с дочкой[/url]

    [url=http://memahuq.herobo.com/art.php?article=maloletnyaya-prostitutka-video]Малолетняя проститутка видео[/url]
    [url=http://memahuq.herobo.com/art.php?article=prastitutki-lyblino]Праститутки люблино[/url]
    [url=http://memahuq.herobo.com/art.php?article=prostitutki-aziatskoy-vneshnosti]Проститутки азиатской внешности[/url]
    [url=http://memahuq.herobo.com/art.php?article=reyting-prostitutok-moskvi]Рейтинг проституток москвы[/url]
    [url=http://memahuq.herobo.com/art.php?article=kak-snyat-prostitutku-v-italii]Как снять проститутку в италии[/url]

    [url=http://www.e-sincap.com/forum/showthread.php?tid=2106]проститутки 2000р москва, проститутки золотой дождь[/url]
    [url=http://xn--e1afats9f.xn--p1ai/logs/guest/index.php?showforum=1]очень дешевые проститутки москвы, дешевые проститутки города москвы[/url]
    [url=http://www.essentialeavesdropping.com/2011/03/29/see-you-coachella-take-3/#comment-10717]проститутки арзамаса, проститутки москвы дешево на ночь[/url]
    [url=http://www.chinastone.com.cn/AD/magazine/default.htm]павлово проститутки, проститутки шоссе москва[/url]
    [url=http://salman.ga2h.com/vb/member.php?1209-gitKereteem]самые дешевые проститутки города москвы, проститутки челябинска фото[/url]

    ·

  23. Hidraulika Author Editor

    Simply wish to say your article is as amazing. The clearness in your post is simply great and i can assume you are an expert on this subject.

    ·

  24. JBK Author Editor

    This is hardly a beginner’s tutorial. The code isn’t explained in the right amount of detail, and a lot of the code is very confusing to beginners.

    ·

  25. Simon Author Editor

    Thanx for the Tutorial. It has really been Helpful. I have been following this tutorial but i have failed to use the user class to update my users. I have only managed to save them into the database. I need Help on the Update function

    ·

  26. zeus Author Editor

    I am a beginner…. is it not viewed as bad form to keep a DB connection open all the time? I was under the impression it was OPEN get what you need, CLOSE immediately to avoid collisions and such. Is this something that is not true? or have I been misinformed?

    ·

  27. kgiFozzjsv Author Editor

    Wholesale Cheap 1:1 replica louis vuitton Handbags / Bags / Purses from china Online Outlet for Sale
    http://joyeyabm3.webs.com/ lgdfbw

    Wholesale Cheap 1:1 replica louis vuitton Handbags / Bags / Purses from china Online Outlet for Sale
    nawlxu

    ·

  28. shyam Author Editor

    nice tutorial….
    thanks for sharing

    ·

  29. ali Author Editor

    Hello mates
    why I am getting these messages when u open the settings.php page
    Warning: unserialize() expects parameter 1 to be string, object given in includes/global.inc.php on line 18
    mysql_num_rows(): supplied argument is not a valid MySQL result resource in classes/DB.class.php on line 43

    mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in classes/DB.class.php on line 26
    thank you

    ·

  30. Dominik Author Editor

    Hello there,

    Tutorial works great! Now, I have been trying to implement a Privileges structure to the page by adding the field to the DB, and assigning it some value, 1,2,3 for example.
    Where 1 stands for user, 2 for mod, 3 for admin.

    But I have not been able to get this to work yet, any help would be apreciated!
    Here is my attempt so far :

    function userAccessRihts($privileges) {
    $db = new DB();
    $db->connect();

    $username = $_SESSION['username'];
    $users = mysql_query(“SELECT auth FROM users WHERE username=’$username’”) or die(mysql_error());
    $fetch = mysql_fetch_assoc($username);
    $privileges = $fetch['auth'];

    if ($privileges ==”1″) {
    echo “Welcome $users->username, you are currently loged in as a User.”;
    } else if ($privileges ==”2″) {
    echo “Welcome $users->username, you are currently logged in as a Moderator. “;
    } else if ($privileges ==”3″) {
    “Welcome $users->username, you are currently logged in as a Administrator. “;
    } else {
    echo “You are currently viewing this page as a guest.”;
    }
    }
    ?>

    this is just a simple message that should display with what access level the current user is logged in, but in all fairness, if I get that to work, the rest is a peace of cake!
    Thanks in advance!

    ·

  31. Bilal Author Editor

    nice tutorial….but please somebody tell me that why didn’t Brian define the usertools functions in the user class itself..??? ..is thr any special need for another class called usertools..? why did declare only one functions in user class i.e. save…? please tell me fast …i’m too confused…!!!

    ·

 

Build Internet by One Mighty Roar. Since 2008.