Web based single-page, light weight HTML editor with auto-save, using HTML, JavaScript and PHP

image

Source Code:

001 <?php
002     /**
003      *  A lightweight, single page HTML editor with live preview and auto-save
004      *  Author: Praveen Nair @ http://blog.ninethsense.com/
005      *  
006      */
007
008     $f $fn "";
009     if (count($_GET) == 1)  {
010         $f key($_GET);
011         $fn "$f.html";
012     } else {
013         die();
014     }
015
016      if ( isset($_POST["c"]) )  {
017         $content $_POST["c"];
018         echo  (file_put_contents($fn$content))?"1":"-1";
019         die();
020     }
021    
022 ?>
023 <html>

024     <head>
025         <meta http-equiv="content-type" content="text/html; charset=utf-8">
026         <style>
027             #tb {
028                 margin-left: 5;
029             }
030             #editor, #preview {
031                 flex: 1 0 0;
032                 background:#eee;
033                 margin: 5 5;
034                 padding: 5 5;
035                 overflow:auto;
036             }
037             #editor {
038                 font-family: monospace;
039             }
040             #preview, a {
041                 font-family: Arial, Helvetica, sans-serif;
042             }
043             [placeholder]:empty::before {
044                 content: attr(placeholder);
045                 color: #ccc; 
046             }
047             #saved {
048                 font-size:8pt;
049                 margin-left:5px;   
050             }
051         </style>
052     </head>
053     <body>
054         <div id="tb">
055             <input type="button" value="Save" onclick="Save()" /><span id="saved"></span>
056             <a href="preview.php?<?=$f?>" target="_blank" style="float:right;font-size:8pt">[Preview]</a>
057         </div>
058         <div style="display: flex;height:90%">
059             
060             <div id="editor" contenteditable="true" onkeyup="LivePreview()" placeholder="Your HTML Code"></div>
061
062             <div id="preview" placeholder="Preview Area"></div>
063         </div>
064
065         <script>
066             var editor = document.getElementById("editor");
067             var preview = document.getElementById("preview");
068             var IsSaved = true;
069             editor.focus();
070             function LivePreview() {
071                 preview.innerHTML = editor.innerText;
072                 IsSaved = false;
073             }
074             function Save() {
075                 var xhttp = new XMLHttpRequest();
076                 xhttp.onreadystatechange = function() {
077                     if (this.readyState == 4 && this.status == 200) {
078                         if (xhttp.responseText == "1") {
079                             document.getElementById("saved").style.color = 'green';
080                             document.getElementById("saved").innerText = "Last saved at " + new Date() ;
081                             IsSaved = true;
082                         } else {
083                             ShowError();
084                         }
085                     } 
086                 };
087                 var formData = new FormData();
088                 formData.append("c", editor.innerText);
089                 xhttp.open("POST", "<?= $_SERVER["PHP_SELF"]. "?$f?>", true);
090                 xhttp.send(formData);
091
092             }
093             setInterval(() => {
094                 if (!IsSaved) {
095                     Save();
096                 }
097             }, 5000);
098
099             ShowError = function() {
100                 var ele = document.getElementById("saved");
101                 ele.style.color = 'red';
102                 ele.innerText = "Couldn't Auto-save. Will retry soon" ;
103             }
104             window.onload = function() {
105                 <?php
106                     $content "";                
107                     if ( $_SERVER['REQUEST_METHOD'] != 'POST' ) {
108                         if (file_exists($fn)) {
109                             $content file_get_contents($fn);
110                         } 
111                         echo "editor.innerText = `$content`;";
112                     }
113                 ?>
114                 LivePreview();

115             }
116             
117         </script>
118     </body>
119 </html>
120

View in GitHub | Made with wp-showgithubfile plugin

WordPress plugin – Show your source code directly from GitHub in your blog/website

Show a file, preferably source code file content in a WordPress blog post or page.  This plugin shows always the latest code from GitHub.

Visit my GitHub repository to download the plugin for free – https://github.com/ninethsense/wp-ShowGithubFile

screenshot

Source Code: (Live Example directly from GitHub 🙂

001 <?php
002 /**
003  * Plugin Name: wp-ShowGithubFile
004  * Description:       Show a file, preferably source code file content in a WordPress blog post or page
005  * Version:           1.0.0
006  * Author:            NinethSense
007  * Author URI:        https://blog.ninethsense.com/
008  * License:           GPL v2 or later
009  */
010
011
012     add_shortcode"GitHub""ShowGitHub" );
013     function ShowGitHub($atts) {
014         if (!isset($atts["file"]) && !strpos(strtolower($atts["file"]), "https://raw.githubusercontent.com/" )) {
015             // Also, I want only files from GitHub. Modify this to show file from any URL
016             return "[Invalid GitHub Raw file]";
017         }
018         
019         $fh = @get_headers($atts["file"]);
020         
021         if (strpos($fh[0],"200") == 0) {
022             return "[Invalid file]";
023         }
024         
025         $fcontents file_get_contents(trim($atts["file"]));
026         $notphp false;
027         
028         if (strpos($fcontents"?php") == false) {
029             $fcontents "<?php ".$fcontents;
030             $notphp true;
031         }
032         
033         // Make use of PHP syntax highlighing. Something is better than nothing.
034         $fcontents highlight_string($fcontentsTRUE);
035         
036         if ($notphp) {
037             $fcontents str_replace("&lt;?php&nbsp;""",$fcontents);
038             $notphp false;
039         }
040
041         $fcontents str_replace(["<code>""</code>"], "",$fcontents);
042         
043         $fcontents explode("<br />",$fcontents);
044         
045         $style = (isset($atts["style"])) ?$atts["style"]:"";
046         $ret "<div style='font-family:monospace;background-color:#dcd7ca;width:100%;overflow:auto;white-space:nowrap;border:solid 1px #aaa;font-size:10pt;$style'>";
047         for ($i=0;$i<sizeof($fcontents);$i++) {
048             $line $fcontents[$i];
049             $ret .= "<span style='font-size:10pt;display:block;width:40px;background-color:#aaa;float:left'>" 
050                 str_pad($i+13,'0',STR_PAD_LEFT) ." </span><span style='margin-left:10px;width:100%;inline-block'>" $line "</span><br />";
051         }
052         $ret .= "</div>";
053        
054         file_put_contents("D:\\test.txt"$ret);
055         return $ret;
056
057         
058     }
059 ?>

View in GitHub | Made with wp-showgithubfile plugin

PHP PortPing script – check host connectivity

Here is a script in PHP I wrote to check if a remote host and port are open for you to connect. Do not mistake this as an equivalent to ping command because ping uses ICMP and I used TCP using PHP’s famous fsockopen() function, and a small piece of AJAX.

PortPing

You can get the latest source code from my GitHub code share page – https://github.com/ninethsense/code-share/

PHP:

function ping($host, $port) {
         $startTime = time();
         if ($fs = fsockopen($host, $port, $errCode, $errStr, 1)) {
             $timeTaken = (time()-$startTime)/1000;
         echo "Reply from $host:$port time={$timeTaken}ms";
             fclose($fs);
         } else {   
             echo "Request timed out.";
         }
         echo "<br>";
     }

JavaScript:

var count = 0;
             var intervalID = setInterval(function PortPing() {
                 var xhttp = new XMLHttpRequest();
                 xhttp.onreadystatechange = function() {
                     if (this.readyState == 4 && this.status == 200) {
                         document.getElementById("console").innerHTML += this.responseText;
                     }
                 };
                 xhttp.open("GET", "PortPing.php?source=self&host=<?=$host?>&port=<?=$port?>", true);
                 xhttp.send();
                 if (++count > <?=$t-1?>) {
                     clearInterval(intervalID);
                 }
             },2);

Ajax file uploader using jQuery

Here is a sample code to upload multiple files using ajax, and without using the traditional <form> tags. Find the full source code in GitHub – https://github.com/ninethsense/code-share/tree/master/jQuery-File-Upload .

<body>
    <input type="button" value="Choose file" id="fup" />

    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>    

    <script>
            $(function() {

                // Show file upload dialog on click of button
                $("#fup").click(function(){

                    //Create File component
                    var fu = document.createElement("input");
                    fu.type = "file";
                    fu.id="fuc";
                    $(fu).attr("multiple","");

                    // Trigger file selection event
                    $(fu).change(function(){
                        var fd = new FormData();
                        $.each($(fu)[0].files, function(i, file){
                            fd.append('file[]', file);
                        });

                        // Send fd to server
                        $.ajax({
                            url:"FileUpload.php",
                            type: 'POST',
                            data:fd,
                            cache: false,
                            contentType: false,
                            processData: false,
                            success: function(d) {
                                console.log(d);
                            }
                        });
                    });

                    // To invoke the file selection dialog box
                    $(fu).click();

                });
            });
    </script>
</body>

Sample server code in PHP for the reference:

foreach ($_FILES['file']['tmp_name'] as $k => $v) {
move_uploaded_file(
$_FILES['file']['tmp_name'][$k],
$_FILES['file']['name'][$k]
);
}