Adding CKEditor to webpages in PHP #Code

What is CKEditor

CKEditor is an open source, customizable web text editor that can be integrated to our webpages. It can be used in three different modes (Article editor, Document editor and Inline editor) for content creation. I was looking for a web editor like Google doc using which I can collect text data from students (but not requiring login with gmail), and I found CKEditor doing exactly what I wanted to do. I’m using it here as a web document editor.

In this blog post, I’m combining a few steps I did to integrate CKEditor to my webpage. This is the code I wrote after a few rounds of trial and error and many rounds of looking up on the CKEditor documentation and StackOverflow. Wish I found a blog like this when I was trying to implement this 😉

Setting up CKEditor

CKEditor is available for download here. I used the Standard package of the current stable version  (Version 4.6.2 • 12 Jan 2017). All you have to do is to copy the folder ‘ckeditor’ from the downloaded zip file to your program files folder and you’re ready to go. The main steps are below:

Include ckeditor.js in the head section of your code:

<!-- make sure the src path points to your copied ckeditor folder -->
<script src="ckeditor/ckeditor.js"></script>

Create a text area for the editor in the body section followed by your CKEditor instance:

<!-- creating a text area for my editor in the form -->
<textarea id="myeditor" name="myeditor" id="myeditor"></textarea>

<!-- creating a CKEditor instance called myeditor -->
<script type="text/javascript">
	CKEDITOR.replace('myeditor');
</script>

This simple full code renders you a CKEditor with the default configuration options (Default toolbar, width, height etc. – All of these can be customized).

Including a default text in CKEditor

To include a default text in the editor, just replace the text within your textarea with your desired text. Include html tags for formatting if needed. Full code below:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Sample CKEditor page</title>
        <!-- src path should point to your copied ckeditor folder -->
        <script src="ckeditor/ckeditor.js"></script>
    </head>
    <body>
        <form>
	<!-- creating a text area for my editor in the form -->
        <textarea id="myeditor" name="myeditor" id="myeditor"> 
		<b>Introduction</b>
		<p> This is the text to be edited which I'm adding to my CKEditor. 
		.......
		<br />
		<b> Conclusion </b>
	    </textarea>

	<!-- creating a CKEditor instance called myeditor -->
	<script type="text/javascript">
		CKEDITOR.replace('myeditor');
	</script>
        </form>
    </body>
</html>
Resizing CKEditor and editing its toolbar

To change the default height and width of the CKEditor, modify your code as below:

<script type="text/javascript">
    //resize CKEditor with customised height and width
    CKEDITOR.replace('myeditor',{
	width: "700px",
        height: "400px"
     }
);
</script>

If you also want to customise your toolbar, you can do so as below:

CKEDITOR.replace( 'myeditor',
    {
        toolbar :
        [
            ['Source'],
            ['Bold','Italic','Underline','Strike'],
        ],
        height: 700,
        width: 400
    });

This code will give you a customized editor with only the tools you selected like this:

Alternatively, if you want to keep most of the tools, but only remove a few buttons, you can update the config.js file of your CKEditor to include this line:

// Remove buttons not needed in the Standard toolbar
config.removeButtons = 'Subscript,Superscript,Maximize,Source,About';

The complete list of buttons is here.

My configured CKEditor now looks like this:

Track changes in text

CKEditor has a plugin called LoopIndex Track Changes to track the changes made to the text inside the editor. This is similar to the Review -> Track changes option in Microsoft Word, which when enabled tracks all changes made to the text. This works like a charm in three easy steps:

1. Download the plugin and copy the ‘lite’ folder to the plugins folder of CKEditor.

2. Add lite-interface.js to your script along with the prior ckeditor.js

<script type="text/javascript" src="ckeditor/plugins/lite/lite-interface.js">
</script>

3. In config.js of the CKEditor, include the following code:

//Adding lite for tracking changes
config.extraPlugins = 'lite';
	
var lite = config.lite|| {};
config.lite = lite;

Now, the editor can track and highlight the changes made to the text:

Saving text from a CKEditor

There are a few ways to save data from the editor. I’m using a post method to get the data from the text area and store it in my mySQL database. This is my submit.php file where I get the data from the editor and store it in my database after cleaning:

<!DOCTYPE html>
<html>
<?php

require ('config.php');

//Function to clean the text data received from post
function dataready($data) {
	$data = trim($data);
	$data = stripslashes($data);
	$data = htmlspecialchars($data);
	return $data;
} 

    $editor_data = dataready($_POST['myeditor']);

	//Decoding html codes for storing in DB
	$editor_data_insert = html_entity_decode($editor_data);
	
	
	$sql="INSERT INTO `editortext` (`ID`, `tstamp`, `text`) VALUES ('', CURRENT_TIMESTAMP, '$editor_data_insert' )" ;

	if (!mysqli_query($con,$sql))
	{
	die('Error: ' . mysqli_error($con));
	}		
?>
</html>

My final code for the editor looks like this:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Sample CKEditor page</title>
        <!-- src path should point to your copied ckeditor folder -->
        <script src="ckeditor/ckeditor.js"></script>
	<script type="text/javascript" src="ckeditor/plugins/lite/lite-interface.js"></script>
    </head>
    <body>
        <form id="editor" action="submit.php" method="post">
		
	<!-- creating a text area for my editor in the form -->
        <textarea id="myeditor" name="myeditor" id="myeditor"> phpIntroduction</b>
		<p> This is the text to be edited which I'm adding to my CKEditor. 
		.......
		<br />
		<b> Conclusion </b>
	    </textarea>

	<!-- creating a CKEditor instance called myeditor -->
	<script type="text/javascript">
	//resize CKEditor with customised height and width

	CKEDITOR.replace('myeditor',{
		width: "700px",
        height: "400px"
        }
	);	
	</script>

       //Adding submit button
	<input type="submit" value="Submit data" class="button"/>
        </form>
    </body>
</html>

I’m also working to see if I can track key strokes or take snapshots of the drafting process. Will write another post when that succeeds 🙂

14 thoughts on “Adding CKEditor to webpages in PHP #Code”

  1. HI,
    I got this part very easily, but I’m wondering if you can help me with this little problem.
    If I put my code in a single file to get a single webpage I get the results. When I introduce it to the main page via get data from another file with a function type like ajax it’s not working, tried multiple solution but no winning one. I’ve put the script tag with the url for ckeditor and still no luck. But if I code it like just one page for a single website page, ckeditor works fine but not when link to another coded page in 2 separate files that gives one website page

    1. I haven’t seen your code, but you CAN get data from another page to load in ck editor. You can use the data from your AJAX call in ckEditor directly.

      Alternatively, try storing the data as a session variable ($_SESSION[‘editorText’] = yourdata), then use that text ($my_text = $_SESSION[‘editorText’] ) when initializing ckeditor like below:
      Inside the textarea for ckeditor:

      Close textarea

  2. hi interesting and didactica your explanation, I have a query how you could implement ckeditor for multiple editors on the same page (2,3, or more), you could give an example. I’m doing some tests and I can not do it. Thank you

    1. You can add as many editors as you want to in a page, just create new ck editor instances. Here’s a sample that worked for me with two:


      <textarea id="myeditor1" name="myeditor1" id="myeditor1">
      <b>Introduction</b>
      <p> This is the text to be edited which I'm adding to my CKEditor window 1.
      .......
      <b> Conclusion </b>
      </textarea>

      <textarea id="myeditor2" name="myeditor2" id="myeditor2">
      <b>Introduction</b>
      <p> This is the text to be edited which I'm adding to my CKEditor window 2.
      .......
      <b> Conclusion </b>
      </textarea>

      <script type="text/javascript">

      CKEDITOR.replace('myeditor1',{
      width: "500px",
      height: "200px"
      }
      );

      CKEDITOR.replace('myeditor2',{
      width: "500px",
      height: "200px"
      }
      );

      </script>

  3. Very nice tutorial and thank you for sharing it!

    Have you ever given thought to providing the working source for download? Would really help newbies like myself. The above code above is a good overview but missing few things for people like myself:)

    Thanks again for sharing your knowledge.

    Susan

    1. Use a placeholder attribute in the text area html tag to include a default text. This will display your placeholder text as a hint before users replace it with their text.

      <textarea placeholder="hinttext"> </textarea>

  4. I’m lost regarding on how to rewrite my current site that already has the older FCKeditor installed. At the moment I cannot see my content or the editor. My content shows on my website, but I’m unable to edit the content on my backend. I installed the ckeditor4 files in my include folder. can I send you my coding for review? Any help would be greatly appreciated.

    1. Hi, I do not do code reviews. If there is a specific problem with a few lines of code, I will see if I can help you debug it. You should be able to edit the content using the ckeditor files in folder as described in my blog post.

Leave a Reply

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