LA(M)P Stack:

    Creating a LAMP Stack in SourceLair

    Introduction

    The goal of this guide is to get your started developing your LAMP stack on SourceLair and make sure you make the most out of our platform.

    Additionally, we'll be talking about adding MySQL support for a database backed dynamic website and how you can work on PHP frameworks in SourceLair.

    This guide assumes that you already have


    So, what is a LAMP stack?

    What is a LAMP Stack

    LAMP stack is a popular open source web platform commonly used to run dynamic web sites and servers. It includes Linux, Apache, MySQL, and PHP and is considered by many the platform of choice for development and deployment of high performance web applications which require a solid and reliable foundation. It's easy to deploy and it's no coincidence that Wordpress and other web platforms are using it to power today's web.


    Let's start by creating a simple application

    Creating a simple PHP application

    As usual, we'll start by creating a simple "Hello World" application, so let's start by opening the index.php file that already exists in your new SourceLair project. The file has the following contents:

    <!doctype html>
    <html>
        <head>
            <meta charset="utf8" />
            <title></title>
            <link rel="stylesheet" type="text/css" href="main.css" />
        </head>
        <body>
            <h1>Hello</h1>
            <?php echo '<p>Welcome to your new PHP project, at SourceLair.</p>'; ?>
        </body>
    </html>
    

    Now, in order to preview your file you have to open your Public URL. Public URLs are unique for each project and are secured with HTTPS. You can find your Public URL in the following places:

    • Open your Public URL from the side bar, by pressing the button with the eye
    • Open your Project Settings, available using the gear icon next to the project name
    • Open your Public URL from Command Palette


    Let's add some color

    Making the application dynamic

    Hey, PHP is here for dynamic applications, not static websites like the one we just created. Let's make our little application dynamic. For example, let's make it load with a different colored text each time. Create a new php tag at the start of the document and create the needed functions there.

    <?php
    /*
     * Creates a random color part, a hex in the range [0, 255].
     */
    function random_color_part() {
        return str_pad(dechex(mt_rand(0, 255)), 2, '0', STR_PAD_LEFT);
    }
    
    /*
     * Generates a random hex color, using 3 random parts.
     */
    function random_color() {
        return random_color_part() . random_color_part() . random_color_part();
    }
    ?>
    <!doctype html>
    <html>
        <head>
            <meta charset="utf8" />
            <title></title>
            <link rel="stylesheet" type="text/css" href="main.css" />
        </head>
        <body>
            <?php
                echo '<h1 style="color: #' . random_color() . ';">' .
                    'Hello</h1>';
            ?>
            <?php
                echo '<p style="color: #' . random_color() . ';">' .
                    'Welcome to your new PHP project, at SourceLair.</p>';
            ?>
        </body>
    </html>
    

    Now that the application is dynamic, just keep refreshing your Public URL and each time it'll load with a new color in the heading and content!


    Speed is the key and our next step

    Speeding up development with Split View

    Public URL is very handy in most cases, but there are times you want to test results right away without switching away from your project. This is why we have created Split View. Split View allows you to see changes right next to your code. To open Split View, just hit Ctrl + Enter (or Cmd on a Mac), or use the "Preview" button, which is above the editor.

    Now, make any change you want - for example remove the dynamic color in the heading - and press save (Ctrl + S or Cmd on a Mac). Tada! Your website automatically refreshes.

    Split View


    How about adding Monolog for better logs now?

    Installing packages

    We will use Composer to install packages in PHP. Composer is one of the most common dependency managers for PHP. In order to define which requirements your application has, you need to create a composer.json file and add packages in the following structure:

    {
        "require": {
            "monolog/monolog": "1.0.*"
        }
    }
    

    Create the file above, since we're going to use Monolog for a quick logging demo in the next step.

    In order to install your composer dependencies in SourceLair, all you have to do is open the Command Palette, type "Composer" and press enter. After the installation finishes, just add the following code in the start of the first php tag and refresh your Public URL a couple of times.

    use Monolog\Logger;
    use Monolog\Handler\StreamHandler;
    
    // create a log channel
    $log = new Logger('name');
    $log->pushHandler(new StreamHandler('warning.log', Logger::WARNING));
    
    // add records to the log
    $log->addWarning('Foo');
    $log->addError('Bar');
    

    As you can see, a new file named warning.log has been created with your logs.

    Fun fact: If you keep the file open and keep reloading the page, you'll see the file being updated in real time!


    Time to connect a database

    Bonus: Adding a database to our project

    When you created your project, there was a step about adding a MySQL database to it. If you chose not to, you can still add a database to your project from the Project Settings - accessible using the gear icon next to the project name - by pressing the "Connect a Database" button.

    Notice: This is a paid feature, but within your first 30 days after signing up, your first database is free, so you can easily test this without spending a cent.

    Now that you have created and connected a MySQL database to your project, let's add a simple visitor counter to our application.

    First, let's create a new database and a new table in MySQL. In your Terminal, type the following to connect to your MySQL.

    mysql -u root -p mysecretpassword -h mysql
    

    Then, type the following commands in the MySQL shell:

    1. create database php_demo;
    2. use php_demo;
    3. create table visitor_counter (_id int auto_increment primary key, time datetime);

    You're set. Add the following function in the first php tag of your index.php file:

    /*
     * Increments the counter by adding a new record and returns the count of all
     * records currently in the database.
     */
    function increment_and_get_total_visitors() {
        $link = mysql_connect('mysql', 'root', 'mysecretpassword');
        if (!$link) {
            die('Could not connect: ' . mysql_error());
        }
        mysql_query('use php_guide');
        mysql_query('INSERT INTO visitor_counter (time) VALUES (now())');
    
        $result = mysql_query('SELECT count(*) as total from visitor_counter');
        if (!$result) {
            die('Count failed: ' . mysql_error());
        }
        mysql_close($link);
        $data = mysql_fetch_assoc($result);
        return $data['total'];
    }
    

    This function connects to the MySQL database, adds a new visitor record, counts the total visitors and returns them. Then, in the second php tag inside the HTML body, add the following code:

    echo '<p>Hello visitor: ' . increment_and_get_total_visitors() . '.</p>';
    

    Now, each time you refresh the page, the counter increases and you get to see the updated counter!


    The complete demo PHP file altogether, yay!

    Complete demo PHP file

    Below is the complete index.php file that we created.

    <?php
    require __DIR__ . '/vendor/autoload.php';
    
    use Monolog\Logger;
    use Monolog\Handler\StreamHandler;
    
    // create a log channel
    $log = new Logger('name');
    $log->pushHandler(new StreamHandler('warning.log', Logger::WARNING));
    
    // add records to the log
    $log->addWarning('Page Loaded!');
    
    /*
     * Increments the counter by adding a new record and returns the count of all
     * records currently in the database.
     */
    function increment_and_get_total_visitors() {
        $link = mysql_connect('mysql', 'root', 'mysecretpassword');
        if (!$link) {
            die('Could not connect: ' . mysql_error());
        }
        mysql_query('use php_guide');
        mysql_query('INSERT INTO visitor_counter (time) VALUES (now())');
    
        $result = mysql_query('SELECT count(*) as total from visitor_counter');
        if (!$result) {
            die('Count failed: ' . mysql_error());
        }
        mysql_close($link);
        $data = mysql_fetch_assoc($result);
        return $data['total'];
    }
    
    /*
     * Creates a random color part, a hex in the range [0, 255].
     */
    function random_color_part() {
        return str_pad(dechex(mt_rand(0, 255)), 2, '0', STR_PAD_LEFT);
    }
    
    /*
     * Generates a random hex color, using 3 random parts.
     */
    function random_color() {
        return random_color_part() . random_color_part() . random_color_part();
    }
    ?>
    <!doctype html>
    <html>
        <head>
            <meta charset="utf8" />
            <title></title>
            <link rel="stylesheet" type="text/css" href="main.css" />
        </head>
        <body>
            <?php
                echo '<h2 style="color: #' . random_color() . ';">' .
                    'Hello</h1>';
            ?>
            <?php
                echo '<p style="color: #' . random_color() . ';">' .
                    'Welcome to your new PHP project, at SourceLair.</p>';
                echo '<p>Hello visitor: ' . increment_and_get_total_visitors() . '.</p>';
            ?>
        </body>
    </html>
    


    Now that we're done, what's next?

    Next up

    Now that you have learnt the basics of PHP, you can either go on and create your own dynamic website, or even better use a framework to make your life easier. There are plenty of them available and below are some links to help you get started:

    Also, you can check out our PHP help page on some more information on what's available for PHP in SourceLair.

    Happy hacking!