
In today’s fast-paced development world, developers often need a quick and efficient way to test out snippets of code. An interactive PHP playground can provide just that—a space to run and visualize code in real-time. In this article, we’ll explore how to build a PHP-based web application where users can write, execute, and see the output of their code dynamically.
Follow this video for complete guidance :
Full Source Code : PHP Playground
<?php // Function to safely execute PHP code function executePHPCode($code) { $tmpfname = 'files/playground'.time(); file_put_contents($tmpfname, $code); ob_start(); try { include $tmpfname; } catch (Throwable $e) { echo "Error: " . $e->getMessage(); } $output = ob_get_clean(); unlink($tmpfname); return $output; } // If this is an AJAX request, execute the code and return the output if (isset($_POST['ajax']) && $_POST['ajax'] === 'true') { $code = isset($_POST['code']) ? $_POST['code'] : ''; $output = executePHPCode($code); // Send the raw output without HTML encoding header('Content-Type: text/plain'); echo $output; exit; } // Initialize default code $code = '<?php // Example with HTML output: echo "<h1 style=\'color: blue;\'>Hello World!</h1>"; echo "<p>This is a <strong>formatted</strong> paragraph.</p>"; echo "<ul> <li>Item 1</li> <li>Item 2</li> </ul>";'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP Playground</title> <!-- Bootstrap CSS --> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet"> <!-- Font Awesome --> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"> </head> <body class="bg-light"> <!-- Navbar --> <nav class="navbar navbar-expand-lg navbar-dark bg-primary mb-4"> <div class="container"> <span class="navbar-brand"> <i class="fa-brands fa-php fs-4 me-2"></i> PHP Playground </span> </div> </nav> <!-- Main Content --> <div class="container mb-4"> <div class="row mb-4"> <!-- Code Editor --> <div class="col-md-6 mb-4 mb-md-0"> <div class="card h-100"> <div class="card-header bg-white"> <div class="d-flex align-items-center"> <i class="fas fa-code me-2"></i> <span class="fw-bold">Code Editor</span> </div> </div> <div class="card-body p-0"> <textarea id="codeEditor" class="form-control border-0 rounded-0" style="height: 400px; font-family: monospace;" spellcheck="false" ><?php echo htmlspecialchars($code); ?></textarea> </div> </div> </div> <!-- Output --> <div class="col-md-6"> <div class="card h-100"> <div class="card-header bg-white"> <div class="d-flex align-items-center justify-content-between"> <div class="d-flex align-items-center"> <i class="fas fa-terminal me-2"></i> <span class="fw-bold">Output</span> <div id="loadingIndicator" class="ms-2 d-none"> <i class="fas fa-spinner fa-spin text-primary"></i> </div> </div> <div class="btn-group btn-group-sm"> <button type="button" id="viewRaw" class="btn btn-outline-secondary active">Raw</button> <button type="button" id="viewRendered" class="btn btn-outline-secondary">Rendered</button> </div> </div> </div> <div class="card-body"> <!-- Raw Output --> <pre id="outputRaw" class="mb-0" style="height: 400px; overflow-y: auto; font-family: monospace;"></pre> <!-- Rendered Output --> <div id="outputRendered" class="mb-0" style="height: 400px; overflow-y: auto; display: none;"></div> </div> </div> </div> </div> <!-- Controls --> <div class="d-flex gap-2"> <button type="button" id="executeBtn" class="btn btn-primary"> <i class="fas fa-play me-2"></i> Execute Code </button> <button type="button" id="clearBtn" class="btn btn-secondary"> <i class="fas fa-trash me-2"></i> Clear Code </button> </div> </div> <!-- Bootstrap Bundle with Popper --> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script> <script> document.addEventListener('DOMContentLoaded', function() { const codeEditor = document.getElementById('codeEditor'); const outputRaw = document.getElementById('outputRaw'); const outputRendered = document.getElementById('outputRendered'); const executeBtn = document.getElementById('executeBtn'); const clearBtn = document.getElementById('clearBtn'); const loadingIndicator = document.getElementById('loadingIndicator'); const viewRaw = document.getElementById('viewRaw'); const viewRendered = document.getElementById('viewRendered'); // Function to execute code async function executeCode() { const code = codeEditor.value; // Show loading indicator loadingIndicator.classList.remove('d-none'); executeBtn.disabled = true; try { const formData = new FormData(); formData.append('code', code); formData.append('ajax', 'true'); const response = await fetch(window.location.href, { method: 'POST', body: formData }); const result = await response.text(); outputRaw.textContent = result; outputRendered.innerHTML = result; } catch (error) { outputRaw.textContent = 'Error: Failed to execute code. Please try again.'; outputRendered.innerHTML = 'Error: Failed to execute code. Please try again.'; } finally { // Hide loading indicator loadingIndicator.classList.add('d-none'); executeBtn.disabled = false; } } // View toggle handlers viewRaw.addEventListener('click', function() { viewRaw.classList.add('active'); viewRendered.classList.remove('active'); outputRaw.style.display = 'block'; outputRendered.style.display = 'none'; }); viewRendered.addEventListener('click', function() { viewRendered.classList.add('active'); viewRaw.classList.remove('active'); outputRendered.style.display = 'block'; outputRaw.style.display = 'none'; }); // Execute button click handler executeBtn.addEventListener('click', executeCode); // Clear button click handler clearBtn.addEventListener('click', function() { codeEditor.value = ''; outputRaw.textContent = ''; outputRendered.innerHTML = ''; }); // Execute code with Ctrl+Enter or Cmd+Enter codeEditor.addEventListener('keydown', function(e) { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); executeCode(); } }); }); </script> </body> </html>
The Concept Behind the PHP Playground
A PHP playground allows users to enter PHP code into a text editor and then run it, with the result being displayed directly on the webpage. This application can be an essential tool for beginners who want to quickly experiment with PHP without setting up a local development environment.
Our PHP playground consists of several components:
- Code Editor: Where users input PHP code.
- Output Display: Where the results of the PHP execution are shown.
- Execution Controls: Buttons that let the user run or clear their code.
Let’s break down how this simple yet effective application works.
Setting Up the Playground: Core Components
The user interface is built using HTML and styled with the popular Bootstrap framework for a clean and responsive design. Here’s how the core components are structured:
- PHP Code Execution: The backend PHP script takes the user’s input (PHP code), writes it to a temporary file, and executes it using include. The output is then captured using output buffering (ob_start() and ob_get_clean()), which allows us to return the result as a plain text response.
- AJAX for Real-Time Execution: When the user presses the execute button, an AJAX request is sent to the server, where the PHP code is executed. The result is returned to the browser, where it’s displayed without the need for a full page reload. This makes the playground interactive and fast, providing an instant feedback loop for the user.
- Output Display Options: Users can choose to view the output in either raw format or rendered HTML format. This feature allows them to see not just the raw PHP output but also how it would appear when rendered in a browser, which is useful for testing HTML and PHP combined.
- Error Handling: In any environment where code execution happens dynamically, error handling is crucial. In our playground, any errors in the PHP code are caught using a try-catch block. If an error occurs during execution, it’s displayed clearly to the user, ensuring they know exactly what went wrong.
Building the Code Editor
The code editor is simply a textarea element that takes the user’s PHP code input. It is designed to be user-friendly and supports larger code snippets. The text area is styled using CSS to resemble a traditional code editor, ensuring an intuitive experience for the user. Additionally, the editor is populated with default PHP code to get the user started immediately.
PHP File Management and Execution Flow
When the user clicks “Execute Code,” the system performs the following steps:
- The entered code is saved to a temporary file using file_put_contents().
- The code is then executed using PHP’s include() function.
- The output generated by the execution is captured using ob_start() and ob_get_clean().
- The temporary file is deleted using unlink() to avoid cluttering the server with unnecessary files.
This process ensures that the user’s PHP code is executed in a safe and isolated environment.
UI and Experience Enhancements
The user interface of the playground is designed for simplicity and usability. Here are some key features:
- Dynamic Output Area: Users can toggle between “Raw” and “Rendered” views to see their PHP output as plain text or as formatted HTML.
- Loading Indicator: While the PHP code is being executed, a loading spinner is displayed, informing the user that the process is ongoing.
- Clear Code: After executing the code, users can clear the editor and reset the output with a simple button click, making it easy to start a new experiment.
Use Cases and Benefits
This PHP playground can be a valuable tool for:
- Learning PHP: Beginners can experiment with PHP code directly in their browser without setting up a local development environment.
- Testing Snippets: Developers can test small pieces of PHP code quickly and efficiently, helping to debug issues or try out new functions.
- Collaboration: It can be used for collaborative learning, allowing students or team members to share code and see results instantly.
Creating a simple and interactive PHP playground can significantly enhance the learning experience for beginners and speed up development workflows for experienced developers. The ability to write, execute, and see the output of PHP code in real time, combined with a clean and intuitive user interface, makes this PHP playground a must-have tool for any web development environment.
With this basic foundation, you can easily extend the playground with more features such as saving code snippets, sharing projects with others, or even adding syntax highlighting to the code editor. The possibilities are endless, and the interactive approach makes PHP more accessible than ever before.