+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

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