Build Your Own PHP Fiddle Tutorial

Please note: The source code in this article is not ready for deployment to a live web server. There are security vulnerabilities, especially with the use of eval() that I will talk about further in the article.  

I thought a nice all-around learning resource would be to build your own PHP fiddle. It takes many attributes into account to build a fully functional fiddler.

I’m not going to use any type of framework, just to keep it simple and easy enough for anyone else to follow and repeat. So for those devs out there who are frowning at the unstructured files, you know why!

This is what we are going to build –

php fiddle tutorial

Planning it out

What are we going to need?

  • Some PHP, of course
  • Some HTML, CSS (Bootstrap 4) and JavaScript
  • A code editor

How are we going to use them

  • First an foremost, the code editor will, of course, edit the code.
  • PHP will be used to execute the fiddles PHP entered by the user and return a result.
  • The HTML, CSS & JavaScript will build our tidy front end, delivering an intuitive experience for the user.

So, with all that pre-planned, let’s begin!

Creating the Fiddle Front End

To hit the turbo button, we will use some Bootstrap for this front-end, but of course, feel free to use your own or simply go God mode and write the CSS from scratch!

Along with Bootstrap 4, we can use already prepped-theme that will fit the purpose to build upon, specifically, https://getbootstrap.com/docs/4.0/examples/sticky-footer-navbar/

It looks something like this –

bootstrap sticky footer template

So, let’s get started with building the front end, proceed through the following steps to create our root directory, extended layout files, and index.php

Step 1

Create a new folder in the root directory of your web server, I used the directory name of phpfiddle

Step 2

  • Create a subdirectory named includes
  • Within the subdirectory create 2 files, one named header.php and the other footer.php
  • In the project folder (phpfiddle) create an index.php file.

Step 3

Add the following code to the specified files listed below –

header.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="PHP Fiddler">
    <meta name="author" content="CodeWall">
    <title>A Custom PHP Fiddle</title>
    <!-- Bootstrap core CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">


    <style>
        /*sticky footer template css*/

        html {
            position: relative;
            min-height: 100%;
        }
        body {
            /* Margin bottom by footer height */
            margin-bottom: 60px;
        }
        .footer {
            position: absolute;
            bottom: 0;
            width: 100%;
            /* Set the fixed height of the footer here */
            height: 60px;
            line-height: 60px; /* Vertically center the text there */
            background-color: #f5f5f5;
        }


        /* Custom page CSS
        -------------------------------------------------- */
        /* Not required for template or sticky footer method. */

        body > .container {
            padding: 60px 15px 0;
        }

        .footer > .container {
            padding-right: 15px;
            padding-left: 15px;
        }

        code {
            font-size: 80%;
        }
    </style>

</head>

<body>

<header>
    <!-- Fixed navbar -->
    <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
        <a class="navbar-brand" href="#">PHP Fiddler</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarCollapse">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item active">
                    <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                </li>
            </ul>
        </div>
    </nav>
</header>

 

footer.php

Note: I’ve purposely swapped out jquery slim for the full version so we have access to the Ajax functionality.

<footer class="footer">
    <div class="container">
        <span class="text-muted">PHP Fiddler</span>
    </div>
</footer>

<!-- Bootstrap core JavaScript
================================================== -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>

 

index.php

<?php
include 'includes/header.php';
?>


    <!-- Begin page content -->
    <main role="main" class="container">



    </main>



<?php
include 'includes/footer.php';
?>

 

With all the above code added, we can now render the page.

Step 4

Navigate to your projects root URL in your browser eg: http://localhost/phpfiddle, you should see something like the following –

php fiddler layout

 

Now, with this all set up, we can do some exciting stuff!

Developing the Fiddle within the front end

Let’s build upon the index.php file, adding a code pane and a results pane. The code pane will allow the user to enter code and the results pane will display the result.

Installing a Code Editor Pane

There are a few syntax highlighting plugins around and having had a good look at the options, for quickness and getting exactly what we need, Ace.js is perfect. Ace.js is a high-performance syntax editor for web-based front-ends and is even open-sourced. If you want to get involved, they have a GitHub repository and are actively encouraging contributions!

Step 1

  • Create a new js folder in the project’s root directory.
  • Create another subfolder named ace
  • Head over to the Ace builds repository and hit the download zip button.
  • Open the zip file after download and extract the contents of src-min to /js/ace

Step 2

Add the following code to the bottom of the footer.php file, before ending body tag and after the scripts for bootstrap.

Note: Take notice of the editor.setTheme and editor.getSession().setMode lines, it is here that we explicitly specify we want to use the Monokai theme and PHP syntax highlighting!

<!-- Include ace syntax highlighter and intialize the editor. -->
<script src="js/ace/ace.js"></script>
<script>

    window.onload = function() {
        var editor = ace.edit("editor");
        editor.setTheme("ace/theme/monokai");
        editor.getSession().setMode({path:"ace/mode/php", inline:true});

    };

</script>

Step 3

Add the following HTML in between the main HTML tags within the index.php file.

<div id="editor" style="height: 100%;">

</div>

Step 4

Render the index.php page and you should see something similar to below –

ace editor php fiddle

Adding a Results Pane

Of course, we now need somewhere that the code execution output will display. This simply needs to be a simple box with a slight background on it. The same height as the code editor with a small amount of space separating the two.

Step 1

Add the following HTML just after the editor div element.

<div id="editor-result" style="height: 400px; background:#e8e8e8;">

</div>

Styling the Code Editor & Results Pane

Now that we have our code editor and results pane, it should look similar to the HTML below –

<main role="main" class="container">
        <div id="editor" style="height: 400px;">

        </div>

        <div id="editor-result" style="height: 400px; background:#e8e8e8;">

        </div>


    </main>

Now we can use bootstrap to ‘flex’ the boxes and have them side by side.

Step 1

Adjust the HTML within the index.php file to look identical below, we do two things in the update –

  • Add a flexbox container around the panes
  • Add some inline styling to each pane element
<div class="d-flex">
            <div id="editor" style="height: 400px; flex:1; width:300px; margin:5px;"></div>

            <div id="editor-result" style="height: 400px; background:#e8e8e8; flex:1; width:300px; margin:5px;padding: 5px;"></div>
</div>

Step 2

Go ahead and render the index.php file again and you should see something just like below –

php fiddle editor and result pane

Adding A Code Execution Button

All we need now for the front end elements is a button to press for the execution of the code. This button will later be hooked up to a JavaScript onClick event that will start the transfer of code to the backend to be executed. But for now, we just want the button there prepared.

Step 1

Add the following HTML to the index.php file, just after the flex container.

<button class="btn btn-success ml-1" id="execute-code-btn">Execute</button>

Quick recap

Now that our full front end is ready, we have a code editor, result pane, a button to execute the code, we can move on to the more interesting stuff.

We now need to write the simple PHP API file and then move back to the front end to hook it all together.

Have a quick check of your index.php file, it should look similar to below –

<?php
include 'includes/header.php';
?>
    <!-- Begin page content -->
    <main role="main" class="container">

        <div class="d-flex">
            <div id="editor" style="height: 400px; flex:1; width:300px; margin:5px;"></div>

            <div id="editor-result" style="height: 400px; background:#e8e8e8; flex:1; width:300px; margin:5px;padding: 5px;"></div>
        </div>
        <button class="btn btn-success ml-1" id="execute-code-btn">Execute</button>

    </main>


<?php
include 'includes/footer.php';
?>

Let’s move on.

Creating the PHP Execution API

Create the API

Within our simple API, we need the following functionality.

  • A file with a POST handler that will execute the PHP and return a result back to the front end.

Step 1

  • Create a new folder in the project’s root directory named api
  • Create a new file inside the api folder named
    • php-execution-api.php

Step 2

Important Note: Using eval() in this way is extremely dangerous if you don’t prepare for unethical users submitting code to your server. Users can essentially submit ANY PHP code they want, so it is up to you to sanitize any potential vulnerabilities before you think about having this live on a production server.  

Add the following PHP code to the php-execution-api.php file.

Note: eval() executes a string of PHP code, and this is all we need! You can read about eval() here.

if(isset($_POST["code"])) {

    eval($_POST["code"]);

}

Hooking up the API to the Front-end.

Now all is left is to get our front end to send the users code to the API to be executed. When we get a response, we simply refresh the result pane with the PHP output!

Step 1

Add the following to the bottom of your footer.php file, after the ace editor initialization –

We use JQuery to detect a click on the ‘Execution’ button, then we use Ajax to make a call to the backend API which executes the PHP code entered within the Ace editor.

Finally, we append the result to the editor-result pane!

$('#execute-code-btn').on('click',function (e) {

        $.ajax({
            type: "POST",
            url: "api/php-execution-api.php",
            data: {code: $('.ace_content')[0].textContent}, // Grab code from .ace_content element.
            //   dataType: "text",
            success: function(result){
                $('#editor-result').html(result);
            }
        });
    })

 

Testing it out

Step 1

Load up the index.php page in the browser and add the following code to the editor –

$myFirstVar = "Var";
echo $myFirstVar;



for ($i = 0; $i < 10; $i++) {
    echo $i;
}


$myFiddleIsAwesome = true;

echo $myFiddleIsAwesome;

Step 2

Hit the execute button!

Step 3

You should now see a result just like below –

php fiddle working output

And that is it!

Git Repository

If you want to download or clone the exact source code, then head on over to my repository here and feel free to do what you please with it!

Summary

Be in no doubt that this fiddle web tool can be made much better, we could add a save button that saves code to the database. And similarly, allow a user to retrieve that code from the database to pick up where they left off. In addition, some type of auto-complete could be introduced to make it almost identical to how some software integrated development environments work. Finally, it could be properly written in the style of a package for Laravel or similar.

I hope you enjoy this as much as I did, and I think that this tutorial is perfect for beginners. It shows quite a lot of aspects of how PHP can work. As mentioned before, if you want the source, go to my repository here.

Last of all, please remember that the use of eval() with $_POST invites any user to submit code to your server and therefore you must be wary of what the user could submit. All users aren’t all good users so this part must be cleverly designed to avoid any security vulnerabilities.

SHARE ON

The Author: Dan Englishby

Build Your Own PHP Fiddle Tutorial
Posted in PHP

You May Also Like

Leave a Reply

Your email address will not be published.