How to Create a Personal Online PHP Editor

by Vincy. Last modified on July 3rd, 2022.

Online editors has cool advantages like, providing live preview of the code and ease of use. Writing the code online in the web browser and executing it on the go provides an amazing experience. It greatly reduces the effort of downloading and installing the software for setting up the local environment to run the codes. It will also be useful to troubleshoot code snippets intuitively.

This article is to create an online code editor for executing PHP scripts. I have used the CodeMirror API for the UI to type and edit the code online. CodeMirror is a JavaScript-based library. It is one of the popular and widely used code editor. I have written a custom logic to get the code and run (interpret) it in the server-side and provide results in the browser.

Note: This example is designed in such a way that, you can deploy in your local environment for your personal use only. This needs to be enhanced to a large extent to put it into public use.

In this online PHP editor example, an editor will be shown on the landing page. Initially, it is loaded with the PHP hello world program. The code in the editor window is editable and the Run action will take the current code from the editor. Also, we can clear and reload the editor window by clicking the Clear and Refresh button controls respectively. These Run, Refresh and Clear actions are performed using jQuery AJAX.

personal-online-php-editor-output

Converting HTML Textarea into Code Editor

This is the HTML code for showing the landing page with an online text editor. Download CodeMirror and integrate it by including the library files that are required to show the editor. By integrating this library, a HTML form text area element can be converted as an editor window.

The code typed in the editor window can be seen in a various mode based on the programming language. For each mode, the library includes separate JavaScript to classify the mode. In this example, the JavaScript files are used for differentiating the mode of languages like PHP, CSS, XML and more.

This editor window is populated with a sample code. By clicking the Run button, the code in the editor will be validated with jQuery script and executed in the server-side and the result will be displayed below the editor. The action controls Run, Clear and Refresh buttons will make this application interactive.

<!DOCTYPE html>
<html>
<head>
	<title>Editor</title>
    <link rel="stylesheet" type="text/css" href="lib/codemirror/lib/codemirror.css">
    <link rel="stylesheet" type="text/css" href="lib/codemirror/theme/ambiance.css">
    <script src="lib/jQuery/jQuery.js"></script>
    <script src="lib/codemirror/lib/codemirror.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="editor-action.js"></script>
    <script src="lib/codemirror/mode/htmlmixed/htmlmixed.js"></script>
    <script src="lib/codemirror/mode/xml/xml.js"></script>
    <script src="lib/codemirror/mode/javascript/javascript.js"></script>
    <script src="lib/codemirror/mode/css/css.js"></script>
    <script src="lib/codemirror/mode/clike/clike.js"></script>
    <script src='lib/codemirror/mode/php/php.js'></script>
    <script src='lib/codemirror/addon/selection/active-line.js'></script>
    <script src='lib/codemirror/addon/edit/matchbrackets.js'></script>
</head>
<body>
<div class="row">
    <textarea class="codemirror-textarea" id="ed_code"></textarea>
    <div class="app-row">
        <button class="btn-action" id="run">Run</button>
        <button class="btn-action" id="clear">Clear</button>
        <button class="btn-action" id="refresh">Refresh</button>
    </div>
</div>
<div class="app-row">	
  <div id="result"></div>
</div>	
    
</body>
</html>

This is the JavaScript code to initialize CodeMirror properties to turn the HTML textarea element into the code editor. In this script, the textarea class reference is used for the library initialization.

<script type="text/javascript">
	$(document).ready(function() {
		var codeEditorElement = $(".codemirror-textarea")[0];
		var editor = CodeMirror.fromTextArea(codeEditorElement, {
			mode : "application/x-httpd-php",
			lineNumbers : true,
			matchBrackets : true,
			theme : "ambiance",
			lineWiseCopyCut : true,
			undoDepth : 200
		});
	});
</script>

Executing Code with Online Editor using jQuery AJAX

First, the editor instance is created by setting the initial properties by using the library function. With the reference of this editor instance, the editor code content will be read and executed. By clicking the Run button, the code typed in the editor window is read by using the getValue() function. The code can be passed to the PHP via an AJAX request and written in a server file.

After writing the editor code in a PHP file code-editable.php, the another AJAX request will be sent in the complete() callback. In the second AJAX request, the code-editable.php file is accessed.  As this file is with the code typed on the editor, it will return the expected output as the AJAX response in a HTML format. This output will be shown in the result container element.

On clicking the Clear button, the editor window will be wiped out by removing the code via jQuery. The Refresh button click event will trigger the reload action to load the editor with the initial Hello Word PHP program.

<script type="text/javascript">
$(document).ready(function(){
	var codeEditorElement = $(".codemirror-textarea")[0];
    var editor = CodeMirror.fromTextArea(codeEditorElement, {
        mode: "application/x-httpd-php",
        lineNumbers: true,
        matchBrackets: true,
        theme: "ambiance",
        lineWiseCopyCut: true,
        undoDepth: 200
      });
    editor.setValue('<?php\necho "Hello World!"\n?>');

	$(document).on('click', '#run', function(e){
		e.preventDefault();
		$("#error").html("").hide();
		var editorCode = editor.getValue();
		if(editorCode != ''){
		$.ajax({
			url: 'file-write.php',
			type: 'POST',
			dataType: 'json',
			data: {"input":editorCode},
			success:function(response){
			},
			complete:function(){
				$.ajax({
					url: 'code-editable.php',
					type: 'GET',
					success:function(response){
						console.log("response:  "+response);
						$("#result").html(response)	;
					},
					error:function(){
						console.log("error: "+response);
						}
					});	
				}
			});

		} else{
			$("#error").html("Code should not be empty").show();
		}

	});

	$(document).on('click', '#clear', function(e){
		e.preventDefault();
		$("#error").html("").hide();
		editor.setValue('');
	});

	$(document).on('click', '#refresh', function(e){
		e.preventDefault();
		$("#error").html("").hide();
		location.reload();
	});
});
</script>

PHP Script to Write Editor Code to a File Dynamically

In this PHP script, the editor code input from an AJAX request is received. Then the code content will be written to a target file. The PHP file functions are used to create the target file pointer to write the code into it. After writing the code to the file, the file pointer will be closed. When you set up this example in your local environment, make sure the code-editable.php target has the write permission.

<?php
$fp = fopen("code-editable.php", "w") or die("Unable to open file!");
$editorCode = $_POST['input'];
fwrite($fp, $editorCode);
fclose($fp);
?>

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “How to Create a Personal Online PHP Editor”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page