How to Build a CodeIgniter Web App on PHPFog

Tweet

PHPFog is a cloud hosting solution for PHP applications. It offers a free shared cloud that includes access to a MySQL database, and the ability to add 3 apps to your account. The main idea behind PHPFog, is that it looks after all the server requirements for you, leaving you free to design and write your application.

In this article, I will explain how to create an account with PHPFog, and set up your first CodeIgniter application. I’ll explain how this is done with the source code for your application being managed through the Git Source Code Management System.

Creating an Account

To get started, all you need to do is sign up for an account. This takes seconds to do, and will give access to to the app console.

signing for an account on PHPFog

Once your account has been registered, you will be presented with the ‘Create your app’ screen. This comes in 2 sections: either a predefined application such as WordPress, or a framework:

Create an Application

create an app on PHPFog

Create an App with a Framework Installation

create a framework installation on PHPFog

Create an App

For this article, I am going to guide you though how to create a skeleton app using the CodeIgniter framework. So in the lower half of the window, click the CodeIgniter icon:

CodeIgniter on PHPFog

Your app will be created straight away, and you will see a screen like this:

app being deployed on PHPFog

Notice that you can launch phpMyAdmin from here, and that the database connection information you need will be presented to you too.

Once the app has finished deploying, you can click the ‘View live site’ button at the top right of the app console. You should be presented with the default CodeIgniter welcome page in a new browser tab:

CodeIgniter up and running on PHPFog

Create an SSH Key

It might be that you have created a public/private key pair on your computer already. But if you haven’t you will need to create one. PHPFog have a very useful guide that explains how to do that. It covers Mac and Windows; the procedure for Linux is much the same as for a Mac.

You need the ssh keys, so that the PHPFog server can communicate securely with your computer. From the account window, click on SSH Keys. Here, you can add the public part of the key you just created:

add your public key on PHPFog

Once your key has been successfully loaded, you will see the success message:

add your public key on PHPFog

Cloning the App to your Computer

Now the fun really starts. I’m going to assume that you already have Git installed on your computer. If you don’t have it you can find it here.

You can use Git to clone the repository PHPFog created for you. If you look at the top right of the app console window, you will see the Git clone url that you need to use:

Git url on PHPFog

Obviously, the url will reflect the domain/account name you have chosen.

Now, you can open a terminal window, change into the directory where you want to store the source code, and then type the clone command:

git clone git@git01.phpfog.com:your-domain.phpfogapp.com your-project-name

You will see Git download the code from your PHPFog app into the directory you named at the end of the clone command. Now you can open the code as a project in your favourite IDE/text editor. Next we’ll make some adjustments to the configuration of the framework, and push the changes back to the PHPFog repository.

Working with the Source Code

The first thing we will do, so that we can use pretty url’s in our CodeIgniter web app, is add a .htaccess file. That will serve as a good quick test of pushing code back to the PHPFog repository too. Here is a .htaccess file you can use with CodeIgniter:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #Checks to see if the user is attempting to access a valid file,
    #such as an image or css document, if this isn't true it sends the
    #request to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    # If we don't have mod_rewrite installed, all 404's
    # can be sent to index.php, and everything works as normal.
    # Submitted by: ElliotHaughin

    ErrorDocument 404 /index.php
</IfModule>

Add this to a .htaccess file in the root directory of the project. Now, back in your terminal window, you can run:

git status

And the reply will show you the newly added file. Do a:

git add .

to stage the file, and then commit the changes:

git commit -am 'add a .htaccess file for pretty url's'

Finally, to send this file to the server, you can push:

git push origin master

Updating the Framework Config

You have just updated the source code on the PHPFog server in the last step. You can’t really see this change yet though. Also, although you have the database configuration information, you still need to add it to the framework so it knows how to talk the the MySQL database.

Update the Database Config

Open the file application/config/database.php and add the database configuration options PHPFog created for you:

$db['default']['hostname'] = 'mysql-shared-02.phpfog.com';
$db['default']['username'] = 'your username';
$db['default']['password'] = 'your password';
$db['default']['database'] = 'your database name';
$db['default']['dbdriver'] = 'mysql';

Commit your changes, and push up to the PHPFog server again. Refresh the site in your browser, and the CodeIgniter default page should appear. You might think nothing has happened, but if the refresh worked without error, in means CodeIgniter is now connecting to your database.

Update the Site Config

Next, we will add the correct site url and remove the index.php file from our url’s since we are using a .htaccess file. Open application/config/config.php:

$config['base_url'] = 'http://your-name-here.phpfogapp.com/';
$config['index_page'] = '';

While we are at it, we will autoload a couple of resources that will be useful. Open application/config/autoload.php, and update the libraries and helpers sections:

$autoload['libraries'] = array('database');
$autoload['helper'] = array('url');

Commit and push your changes.

Proving Things Work

We are now ready to do some coding that will actually affect the web site in a way that we can see. Open application/views/welcome_message.php and copy the contents into a new file called page2.php in the views folder. Then open application/controllers/welcome.php, and create a new method:

public function page2()
{
    $this->load->view('page2');
}

Then, you can make a minor change to application/views/welcome_message.php:

<div id="body">
    <p><?=anchor(base_url() . 'welcome/page2', 'Go to page 2')?></p>

We are using CodeIgniters’ url helper here. You can do something similar in application/views/page2.php:

<div id="body">
    <p><?=anchor(base_url() . 'welcome', 'Go to the home page')?></p>

Commit and push your changes, then try it out in your browser:

CodeIgniter with code updates on PHPFog

CodeIgniter with code updates on PHPFog

Here, we can see that our simple code updates got pushed to the server, and we can also see that our pretty urls are working.

Testing the database

I created a simple table called ‘notes’ via the phpMyAdmin installation provided by PHPFog. I added the following fields: id, title, note. Then I created a couple of test notes.

Back in your editor, create a new file in application/models called ‘notes_model.php’. Then add a method for retrieving all the notes:

<?php
class Notes_model extends CI_Model
{
    public function __construct()
    {
        parent:: __construct();
    }

    public function get_notes()
    {
        $data = array();
        $sql = "SELECT * FROM notes";
        $q = $this->db->query($sql);
        if($q->num_rows() > 0)
        {
            foreach($q->result() as $row)
            {
                $data[] = $row;
            }

            return $data;
        }
        else
        {
            return 0;
        }
    }
}

Now we need to hook up the model to a method in the controller (application/controllers/welcome.php):

public function page2()
{
    $this->load->model('notes_model');
    $data['notes'] = $this->notes_model->get_notes();
    $this->load->view('page2',$data);
}

Here, you can see that we are loading our notes model, calling the ‘get_notes()’ method, and assigning the results to an array ($data) that can be passed to the view.

In application/views/page2.php add the following code:

<div id="body">
    <p><?=anchor(base_url() . 'welcome', 'Go to the home page')?></p>
    <?php if($notes > 0):?>
    <?php foreach($notes as $n):?>
        <p>
            <?=$n->title?><br />
            <?=$n->note?>
        </p>
    <?php endforeach;?>
    <?php else:?>
        No notes found.
    <?php endif?>

Add, commit, and push your changes, then check the results in your browser:

CodeIgniter with MySQL on PHPFog

Conclusion

PHPFog makes it really easy to set up and deploy PHP web apps to the cloud. You don’t have to worry about the server set up, or databases, or any updating. It is all done for you. Coding on the cloud also makes it possible to streamline your own development tool chain too, since all you really need, is a text editor and Git. No more FTP pain!

Ignition of match with smoke via Shutterstock

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Sameh R. Labib

    Thanks for the article. I’m not ready for PHPFog yet! However, this gives me a good idea what to expect.

  • henry

    I have heard a lot about cloud computing but never really understood how it works. This tutotial has really opened my understanding on cloud computing. Now I can migrate my yii application to the cloud while my data are beign synchronized. Please is it possible to use my own domain instead of using domain.phpfog.com.

    Please kindly explain

    • Amin

      Hi, that’s my page that allwos no comments. I used to have commenting through haloscan, but they shut down (or at least shut down their free service). Setting up Disqus has been on my to-do list for a long time.Thanks for the tip on file_put_contents()! I’ll update my page.

  • ValidCharacter

    Great article. Thank you very much. Only thing that doesn’t sit right with me is you use CodeIgniter and disregard the power of the active record class to a certain extent.

    The model could’ve just read;

    public function get_notes() {
    return $this->db->get(‘notes’)->result();
    }

    That way there is only one “return” out of the model and it is much simpler to read! Your page2.php view will not need to be changed from what you have above!

    Thanks again! I appreciate how you’ve combined some great technology all into one easy to understand article.

  • Bill

    Great post. I hadn’t heard of PHP Fog before, thanks for that tip. This could come in very handy.

  • SJordan

    In this example, you showed how to commit database access details to git and push them up to the remote PHPFog repository. I’ve always been made to believe that we should never commit sensitive data such as usernames and passwords to repositories. However, often these details are needed in config files. I’ve been made to believe that the best approach is to commit a “template” config file such as config.php.temp. Then when a developer or site admin or whomever checkouts out the site, they change the config.php.temp to config.php and enter the access details. In production systems, the “checkout” might be done with automated scripting such as ant. Can you demo how this flow would work — using config templates and deploying to production?

    Thank you