+40 745 232 788

Online Solutions Development Blog   |  


Facebook Quiz in PHP

posted by ,
Categories: PHP
Taggs , , ,

Hello! Today we published a facebook application consisting of a PHP Quiz on our page and in the following article I will let you know what were the steps needed to create it. Most people realized that facebook applications are a great way to promote a business and more and more customers require such apps from us, the web developers and this is why we decided to show how a simple one is developed and also to include some of the key requirements that come from clients (at least from our experience).

What we propose to do?

In this post I will present a fast and easy way to create a Facebook application that will represent a PHP Quiz like this one: PHP Quiz. In order to do this, we will use PHP for developing. This type of application are usually created for promoting a Facebook page. Considering this most of the time you will need to ask the visitors to like the host page before using the app. We will cover this first and after that we will create the set of questions, display them, reckon the final grade and, if the user wants so, we will post a diploma in his gallery.

Registering the application

First we need to register our new application. To do so you must visit https://developers.facebook.com/apps and click on “Create New App” button and you will see a new window that looks like this:

Create App Form

Here we only need to insert our new application name. After we pass the security check the details of our application will be displayed. We will need to provide the Canvas URL, Page Tab Name and Page Tab URL. The Canvas URL will be the address of our application, because it will be like any other web application, but it will work inside Facebook. So we will host the new app on an external server and we will integrate it in facebook as a page tab.

Canvas Form

Tab Form

Starting the development

After we apply the settings it’s time to develop the application and for this we will need the Facebook SDK for PHP. The source code of the two required files can be found by accessing the following links: base_facebook.php and facebook.php. Our project must contain both these files.

We will interact with the user details by using a Facebook object and in order to create it we need the application ID and secret key which were available in the above mentioned application page and you can see later by using an url like: https://developers.facebook.com/apps/YOUR_APP_ID.

$facebook = new Facebook(array(
        'appId' => FACEBOOK_APP_ID,
        'secret' => FACEBOOK_APP_SECRET,
        'cookie' => true,
        'fileUpload' => true

Requesting like

We also want that the user to like our page before he can start using the application. So we check if the visitor already liked it and if not we will display a message.

$signed_request = $facebook->getSignedRequest();

$like_status = $signed_request['page']['liked'];

if (isset($_POST['fp_pass']) && '1' == $_REQUEST['fp_pass'])
    $like_status = 1;

if ($signed_request && !$like_status)
    //display get like page

If the user liked the host page will proceed to our regular routine: the quiz.

Structuring data

The questions that will be displayed will be saved in the database in three tables: one for question categories, one for questions that belong to one of the categories and one for the answers, having the question id and a flag for the right one. Of course that this is just one idea and you are free to save them how you want.
All the questions will be displayed in the same page so we will use the $_SESSION array to save which is the current question and the given answers. Here you have a sample on how we can set the default values or reset the information in the array used to store the quiz progress.

if (isset($_SESSION['reset_answers']))
    if (isset($_SESSION['answers']))

    if (isset($_SESSION['current_question']))


if (!isset($_SESSION['current_question']))
    $_SESSION['current_question'] = 1;

if (!isset($_SESSION['answers']))
	$questions_keys = array_keys($questions);
    foreach ($questions_keys as $question_id)
        $_SESSION['answers'][$question_id] = false;

Navigating through questions

All our questions are displayed in the same page and now all we need to do is to save the current question in the $_SESSION array.  When the users submits an answer, we check if it’s valid. If so, we increment the current question index and if the following question exists, we display it. If not we show the final page. When the user answers a question, we also save the timestamp of this action if you later want to extend the quiz to provide the ability to generate reports about the time needed by the users to pass the test. My approach was something like:

if (isset($_POST['post']))
        $question_id = $_SESSION['current_question'];
        $answer_id = filter_input(INPUT_POST, 'answer_id', FILTER_VALIDATE_INT);
        $_SESSION['answers_to_save'][$questions[$_SESSION['current_question']]['question_id']] = array();
        $_SESSION['answers_to_save'][$questions[$_SESSION['current_question']]['question_id']]['value'] = $answer_id;
        $_SESSION['answers_to_save'][$questions[$_SESSION['current_question']]['question_id']]['time'] = $request_timestamp;

        if (isset($questions[$question_id]))
            if (isset($questions[$question_id]['answers'][$answer_id]))
                $_SESSION['answers'][$question_id] = $answer_id;

            //refresh page
            //redirect to complete page

Generating and uploading diploma

For the diploma we will use the PHP GD library to create the image, save it temporary on the server and upload it to our visitor’s gallery, only if he wants to. We also need a template image, that will be the static part of the diploma. On that we will display the name and the grade for the current user. We will display now the code for this two actions:
Creating the image:

$image = imagecreatefromjpeg('path/to/your/image.jpg');
$name_color = imagecolorallocate($image, 168, 174, 197);
$grade_color = imagecolorallocate($image, 255, 255, 255);
$font = 'path/to/your/font.ttf';
imagettftext($image, 36, 0, 125, 479, $name_color, $font, $name);

if(10 > $grade)
    imagettftext($image, 100, 0, 656, 360, $grade_color, $font, $grade);
    //if the grade it's longer than one digit, we will need a different positioning
    imagefttext($image, 100, 0, 608, 360, $grade_color, $font, $grade);

Uploading the image:

$photo_details = array(
    'message'=> $name .' completed the OSD PHP quiz. Check your knowledge too by taking this test: '. $fbconfig['appBaseUrl']
$photo_details['image'] = '@path/to/your/image.jpg';
$upload_photo = $facebook->api('/me/photos', 'post', $photo_details);

This way, if the user agrees to view the right answers, the diploma will be uploaded in his gallery.

Now you can see how simple and fast it is to create our own Facebook application. Don’t forget that you can take our PHP Quiz and if you do we would like it if you come back and let us know what you think about it.

Update: as some readers requested we uploaded an archive with the source sample here. Please note that the source code is based on the application we are using but details specific to our organization were removed (like facebook app credentials or even the design we are using). Also consider that for this small app we used an open source template engine part of PEAR called Template IT. You are free to use it like this or to replace with any other system you might want, the code is open source. Thank you for your feedback.

If you liked this post
you can buy me a beer

42 Responses to Facebook Quiz in PHP

  1. Can we get a zip file of the same?
    I want to see how result is posted on user’s wall.

    • Hello, Abhishek. At the moment the colleague that wrote this blog post is not available, I will ask him to create an archive with the sources for this tutorial. In the mean time I can say that the process to post the update on the user’s wall is the one you can see in the last code sample (the one that ends with $facebook->api(‘/me/photos’, ‘post’, $photo_details);)
      Where $facebook is the object created in the first code sample ($facebook = new Facebook(…) )
      This will work as long as the user agreed to use your application and allowed it to post updates.

  2. Thank you.

  3. Hi! Very nice app!
    Can we get a zip file of the same?

    • Hello,

      Thank you for your feedback. We did not upload the sources for this facebook app as there are a lot of parts that are very particular to our setup. But it seems that you are not the only one asking this so we will try to clean up the source code and we will make it available as soon as we get the time.

  4. Can I buy app later? When?

    • Sorry, I don’t know what you mean. If you are referring to the source code samples, we usually provide those for free. We will just remove any specific details (like our credentials for the facebook app) and update the article to link to an archive with those files. You will just have to set up the application with your own details.

      Everything that is available as a tutorial on this blog is provided in an open source manner. If you want any specific customizations (that might exceed the purpose of this single blog post) please feel free to use the contact form and we can discuss in private what any custom development might involve (charges, time needed etc)

    • Hello Krisztian,
      I updated the post content and added a link to an archive with the source code for this sample. Please check the notes added as well. Thank you for your feedback and I hope that the sources will help you.

  5. Hi,

    Thanks for the source sample.

    I’m having problems with it though as it’s showing the answer id next to the radio check boxes which isn’t really very useful and I’m struggling to get it to show the answer_text.

    It’s a long time since I’ve programmed in php (and I failed miserably on your test lol) but I am finding a lot of errors in the code, partly due to you using an old template package (I found a call to a “render” function which does exist in the IT.php file hosted by hostgator) and partly I think from the editing to remove information specific to your organization.

    I think that’s a pity because the final result does not reflect well on your organisation in spite of the app you have on facebook working.

    Kind regards,


    • Hello, Anne.

      First of all, regarding the error you are getting for the call to the render method: that is caused by the fact that in the used quiz an customized version of that class was used. This was one of the things that represented an edit specific to our team so it was removed but that call was still there. You could have just removed that line and everything should have worked fine. I updated the archive and the footer.php file doesn’t include that line now. In our class that extended the PEAR version we implemented a way to buffer the content that was rendered only at the end (to be able to use the header function after the app header is completed for example). So we are not using an “old template package” as you say, we are usually extending that class to include other features that we need (like the one mentioned above).

      Regarding the answer text: I checked the sources and its value is sent to the template by this line from modules/index.php

      $tpl->setVariable('ANSWER_LABEL', $answer['text']);

      And it is used in the HTML template as {ANSWER_LABEL}, as it should.

      It is true, a lot of elements were removed to be sure that some sensitive details are not public so that might make things a bit harder as you will have to reconstruct the mini-app. If you say that “It’s a long time since I’ve programmed in php (and I failed miserably on your test lol)” maybe you should take the time to focus on some PHP tutorials first, before getting to build Facebook apps using it. It is not the purpose of this tutorial to teach anyone a programing language, it is just meant to show a few ideas on how to construct such an app, and the written tutorial should be enough most of the time.

      I am sorry that you feel that “the final result does not reflect well on your organisation” but, as previously mentioned with some occasions, this blog is just a hobby for some of the developers that are part of our team, it is not meant to indicate in any way the approach that we, as a company, would have on each particular job. Some indications that might work as a disclaimer for this blog can be found in the article talking about our traffic. We will never cover on this blog technical details on tasks that we had to complete for our customers as the intellectual property for those items is owned by the clients. So all the elements you can find on this blog, like the current article, are the sole opinions of single developers that are part of our team. Even if we try to provide the best quality for these blog posts, the sources do not go through the same quality control steps so this is why the feedback from readers is very important.

      It is normal that from time to time some tools, like that PEAR package, that we used before in other projects will be included but this will be true only for 3rd party elements and, as you can see, we will strip any content that is too specific to our team.

      As you said, “the app you have on facebook working“, we have a very similar version running on our server and, as you can see in etc/settings.php, the error reporting level is set to E_ALL and nothing is tracked in the php error log. If you say that you are “finding a lot of errors in the code” you can post comments regarding each of them and someone will get back to you. If you will have more specific questions Bogdan, the post author, will reply to you, I just got involved with these general aspects and because I was the one to write that list of 10 questions used as samples for this small app.

      As a conclusion I would recommend you to try to learn PHP before using it to build apps in it and if you are interested in specific support for some parts from this tutorial we are happy to reply, as soon as someone that is able to has the time.

      • It’s OK thanks, I’ve put together a much lighter, simpler quiz app for facebook that works fine. All I have left to do now is create 2 videos and I’m ready to roll with it.

        • Hello, Anne. I am glad to hear that you found a solution to your problems. I am sure that you will manage to complete your work as it seems that you are very persistent in your research. Good luck 🙂

  6. you can try ilearn24x7.com/online-skill-quiz-test

    the site is good if you want to determine your skills in php, java etc field.

    I tried mine too !!

    • I determine my php skills by what I can produce with it 🙂

    • Hello, rohitverma. I want to let you know that I removed the link from both your user website and from your comment as it is broken (it shows a 404 error). I can see that you want to promote this website but the purpose of this article was to show how to develop the quiz and not necessarily the questions in it that are just some basic trivia questions. This kind of questions are both simple and do not show a certain level of understanding of PHP and also irrelevant for representing someone’s skills. One could be able to answer all these questions but also lack other important concepts and, on the other hand, a good developer could just forget a certain small detail that will always be available on php.net anyway.

      I will keep this comment here but future similar ones will be considered attempts to promote websites by spamming our comments.

  7. Hi all !

    Downloaded the application, but to me nothing is displayed …
    all set in the config file, that does not work …

    Can anyone help me out?
    Web address: https://apps.margitsziget.info
    FB app: https://apps.facebook.com/margitsziget_kviz/


    • Hello,

      All we can see from those links are some blank pages. Do you have any more details? Errors written to the error log or that show up if you turn on display_errors?

  8. Hi, I can’t find the AppInfo.php in the zip file. I’m not good at PHP. Could you please send the content of AppInfo.php here.

    Thank you very much

  9. I also have the blank page on facebook app. May be your zip file have some missing code.
    There is no error logs. I don;t know to debug from where.

    • The logic should be all there but the configuration part is obviously not added as it is specific to each application. Things like the database connection credentials, the path to the files, the facebook app id and secret are yours and you will need to update them in the settings file.

  10. Hello, thank you for the tutorial. Unfortunately I have some problems, too.

    When I go to (direct URL here), it shows me following error message:

    Parse error: syntax error, unexpected T_VARIABLE in /path/to/etc/settings.php on line 37

    Line 37 in settings.php: $remote_addr = ”;

    Is it supposed to be blank? There was no FILL IN comment.

    If I go to (facebook URL here) it just shows a blank page.

    I entered all the necessary data in the config.php and settings.php

    What did I do wrong? Thank you in advance

    • Hello,

      First of all I would like to say that I edited some data from your comment for you privacy and/or security to mask things like paths on your server or the direct URL to your application.
      To get to the point: yes, the variable is supposed to be empty, that is what we call an initialization. The variable is overwritten later with a different value depending on some conditions, but it won’t stay empty. Also usually these errors (unexpected T_VARIABLE) usually don’t mean that the 37th line is wrong. Instead it must mean that the parser did not expect that variable that is found on that line. Usually this is caused by missing a semicolon on the previous line.

      If you are using the same structure as we do check the dev_ips array (if you used apostrophes when adding values in it or if you have a semicolon after it). If you still can’t find the problem please show us a screenshot of a few lines surrounding line 37 (something like 5 before and 5 after should be enough). From what I see there shouldn’t be any sensitive information in that area.

      • Hello, thank you for the quick help. I had indeed missing a semicolon. Now, if I go to the quiz on my server, it doesn’t show the php message anymore. Unfortunately, the page is still blank. I have the suspicion that something is wrong with the database. I created one. Your settings file require me to enter TABLE PREFIX. Unfortunately my server-backend-interface doesnt have this option. I only can enter database name, password and “comment”, which isn’t the TABLE PREFIX, is it? Also no tables are created when I create the database. Will this be done by your script or do I have to create them manually?

        Here is the snippet of the code:

        /*** UTILS ***/
        define('HTML_CHECKED', ' checked="checked"');
        define('HTML_SELECTED', ' selected="selected"');
        define('HTML_DISABLED', ' disabled="disabled"');

        // reserved ip addresses for development..
        $dev_ips = array();

        // set real client ip address
        $remote_addr = '';
        if (isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
        $remote_addr = $_SERVER['HTTP_CLIENT_IP'];
        elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']))//to check ip is pass from proxy
        $remote_addr = $_SERVER['HTTP_X_FORWARDED_FOR'];
        elseif (isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR'])) // most of the time this will be the ip address
        $remote_addr = $_SERVER['REMOTE_ADDR'];

        Thank you again for your help.

        • Hello,

          The table prefix is the common part that is used to start the names for database tables. If you ran the database dump that comes with the archive without changing anything it should be “onb_fb_”

Add a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Also, if you want to display source code you can enclose it between [html] and [/html], [js] and [/js], [php] and [/php] etc