当前位置:网站首页>Thinkphp6 using kindeditor
Thinkphp6 using kindeditor
2022-06-26 04:26:00 【Shrimp stuff】
kindeditor Official website :http://kindeditor.net/demo.php
Preface
kindeditor Is a good text editor , Can be used in PHP In the project , It's just his PHP The code is native PHP, also PHP The version is a little old , If you want to use thinkphp in , It needs a little modification , And need to be encapsulated in the form of a class
The environment used in this article is thinkphp6,PHP7.4 edition
download
Download it yourself !
Start
1. Copy file
First, put the files you need into your tp In the project , I'm here public/static Under the table of contents , Created a user/kindeditor Folder , Then the following 4 Copy files and folders to the above directory
‘lang’ ‘plugins’ ‘themes’ ‘kindeditor-all.js’

among ‘kindeditor-all.js’ I changed my name to ‘kindeditor.js’, It's ok if you don't change it , Or copy it ‘kindeditor-all-min.js’ The effect is the same , Change according to your own needs , If you don't change your name , Remember to change the code in the reference section that follows me
2. Change reference address
First change js And css Reference address of

It's changed to read as follows :
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>KindEditor PHP</title>
<!-- Mainly the following 5 That's ok -->
<link rel="stylesheet" href="/static/index/kindeditor/themes/default/default.css"/>
<link rel="stylesheet" href="/static/index/kindeditor/plugins/code/prettify.css"/>
<script charset="utf-8" src="/static/index/kindeditor/kindeditor.js"></script>
<script charset="utf-8" src="/static/index/kindeditor/lang/zh-CN.js"></script>
<script charset="utf-8" src="/static/index/kindeditor/plugins/code/prettify.js"></script>
<script>
KindEditor.ready(function(K) {
var editor1 = K.create('textarea[name="content1"]', {
cssPath : '../plugins/code/prettify.css',
uploadJson : '../php/upload_json.php',
fileManagerJson : '../php/file_manager_json.php',
allowFileManager : true,
afterCreate : function() {
var self = this;
K.ctrl(document, 13, function() {
self.sync();
K('form[name=example]')[0].submit();
});
K.ctrl(self.edit.doc, 13, function() {
self.sync();
K('form[name=example]')[0].submit();
});
}
});
prettyPrint();
});
</script>
</head>
<body>
<form name="example" method="post" action="demo.php">
<textarea name="content1" style="width:700px;height:200px;visibility:hidden;"></textarea>
<br />
<input type="submit" name="button" value=" Submission " /> ( Submit shortcut key : Ctrl + Enter)
</form>
</body>
</html>
Complete the above steps , The following effects can be achieved

But then you will find , Uploading pictures is useless , One more prettify.css Will be submitted to the 404
Then change script The code in
Mainly change here

The modified code is as follows
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>KindEditor PHP</title>
<!-- Mainly the following 5 That's ok -->
<link rel="stylesheet" href="/static/index/kindeditor/themes/default/default.css"/>
<link rel="stylesheet" href="/static/index/kindeditor/plugins/code/prettify.css"/>
<script charset="utf-8" src="/static/index/kindeditor/kindeditor.js"></script>
<script charset="utf-8" src="/static/index/kindeditor/lang/zh-CN.js"></script>
<script charset="utf-8" src="/static/index/kindeditor/plugins/code/prettify.js"></script>
<script>
KindEditor.ready(function(K) {
var editor1 = K.create('textarea[name="content1"]', {
cssPath : '/static/index/kindeditor/plugins/code/prettify.css',
uploadJson : 'upload_json',
fileManagerJson : 'file_manager_json',
allowFileManager : true,
afterCreate : function() {
var self = this;
K.ctrl(document, 13, function() {
self.sync();
K('form[name=example]')[0].submit();
});
K.ctrl(self.edit.doc, 13, function() {
self.sync();
K('form[name=example]')[0].submit();
});
}
});
prettyPrint();
});
</script>
</head>
<body>
<form name="example" method="post" action="demo.php">
<textarea name="content1" style="width:700px;height:200px;visibility:hidden;"></textarea>
<br />
<input type="submit" name="button" value=" Submission " /> ( Submit shortcut key : Ctrl + Enter)
</form>
</body>
</html>
Wrong report prettify.css No more mistakes , Solve the problem of uploading pictures, and then look down
3. To upload pictures
Upload the following two files to a folder in the same directory as the editor's controller
For example, my editor is made up of index project index Controller index Method rendering
that , The following two files should be uploaded to "app/index/controller" Under the path
Upload will txt Delete the suffix

After the upload

And then in index.php Introduction in "JSON.php" file

And in index.php Add two public methods to the "upload_json" And "alert"
take kindeditor Medium upload_json.php The code in is copied into "upload_json" And "alert" In the method
The final effect is as follows
( There are many problems in this code , If you don't want to see the wrong process , You can turn directly to the last part of this chapter , Have the correct source code )
<?php
namespace app\index\controller;
use app\BaseController;
use think\facade\View;
require_once 'JSON.php';
class Index extends BaseController
{
public function index()
{
return View::fetch();
}
public function upload_json(){
$json = new \Services_JSON();
$php_path = dirname(__FILE__) . '/';
$php_url = dirname($_SERVER['PHP_SELF']) . '/';
// File save directory path
$save_path = $php_path . '../attached/';
// File save directory URL
$save_url = $php_url . '../attached/';
// Define the file extensions allowed to upload
$ext_arr = array(
'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
'flash' => array('swf', 'flv'),
'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'txt', 'zip', 'rar', 'gz', 'bz2'),
);
// Maximum file size
$max_size = 1000000;
$save_path = realpath($save_path) . '/';
//PHP Upload failed
if (!empty($_FILES['imgFile']['error'])) {
switch($_FILES['imgFile']['error']){
case '1':
$error = ' exceed php.ini Allowed size .';
break;
case '2':
$error = ' Exceeds the allowed size of the form .';
break;
case '3':
$error = ' Only part of the picture was uploaded .';
break;
case '4':
$error = ' Please choose a picture .';
break;
case '6':
$error = ' Cannot find temporary directory .';
break;
case '7':
$error = ' Error writing file to hard disk .';
break;
case '8':
$error = 'File upload stopped by extension.';
break;
case '999':
default:
$error = ' Unknown error .';
}
alert($error);
}
// When uploading files
if (empty($_FILES) === false) {
// original file name
$file_name = $_FILES['imgFile']['name'];
// Temporary file name on the server
$tmp_name = $_FILES['imgFile']['tmp_name'];
// file size
$file_size = $_FILES['imgFile']['size'];
// check filenames
if (!$file_name) {
alert(" Please select a file .");
}
// check directories
if (@is_dir($save_path) === false) {
alert(" Upload directory does not exist .");
}
// Check directory write permissions
if (@is_writable($save_path) === false) {
alert(" Upload directory does not have write permission .");
}
// Check whether it has been uploaded
if (@is_uploaded_file($tmp_name) === false) {
alert(" Upload failed .");
}
// Check file size
if ($file_size > $max_size) {
alert(" Upload file size exceeds limit .");
}
// Check the directory name
$dir_name = empty($_GET['dir']) ? 'image' : trim($_GET['dir']);
if (empty($ext_arr[$dir_name])) {
alert(" The directory name is incorrect .");
}
// Get file extension
$temp_arr = explode(".", $file_name);
$file_ext = array_pop($temp_arr);
$file_ext = trim($file_ext);
$file_ext = strtolower($file_ext);
// Check extension
if (in_array($file_ext, $ext_arr[$dir_name]) === false) {
alert(" Upload file extension is not allowed .\n Only " . implode(",", $ext_arr[$dir_name]) . " Format .");
}
// Create folder
if ($dir_name !== '') {
$save_path .= $dir_name . "/";
$save_url .= $dir_name . "/";
if (!file_exists($save_path)) {
mkdir($save_path);
}
}
$ymd = date("Ymd");
$save_path .= $ymd . "/";
$save_url .= $ymd . "/";
if (!file_exists($save_path)) {
mkdir($save_path);
}
// New file name
$new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
// Moving files
$file_path = $save_path . $new_file_name;
if (move_uploaded_file($tmp_name, $file_path) === false) {
alert(" Failed to upload file .");
}
@chmod($file_path, 0644);
$file_url = $save_url . $new_file_name;
header('Content-type: text/html; charset=UTF-8');
$json = new Services_JSON();
echo $json->encode(array('error' => 0, 'url' => $file_url));
exit;
}
}
public function alert($msg) {
header('Content-type: text/html; charset=UTF-8');
$json = new Services_JSON();
echo $json->encode(array('error' => 1, 'message' => $msg));
exit;
}
}
You are accessing the editor
Will find JSON.php The document will report an error

Mainly because :
PHP7.4 The use of curly braces to access arrays and string offsets is no longer supported _PHP Code
php7.4 Arrays are not supported {} How to write it , Unified as array []
so , Of the above error reports {} Change it to [] that will do , But you will find that there are many places to use {}, So you can copy my code directly and use it normally
Then it needs to be in public Create one in the directory 'attached' Catalog
Trying to upload a file

Discovery or failure , It needs to be changed “upload_json” The code in
The following codes will be

Change it to :

also alert The reference method of this method should also be changed

Change it to :

be-all alert All need to be changed
Submit the document here , Discover and save ,alert Method error reporting

It's already new Once this JSON 了 , So just send it directly
So change here alert
Receive one more json

When called , Pass one more json, Again , be-all alert All need to be changed

Try uploading here
It will also report mistakes , And no error message is displayed

After a close look at the code , Find more new Once

Delete this line to upload successfully
The final code
<?php
namespace app\index\controller;
use app\BaseController;
use think\facade\View;
require_once 'JSON.php';
class Index extends BaseController
{
public function index()
{
return View::fetch();
}
public function upload_json(){
$json = new \Services_JSON();
$php_path = dirname(__FILE__) . '/';
$php_url = dirname($_SERVER['PHP_SELF']) . '/';
// File save directory path
$save_path = 'attached/';
// File save directory URL
$save_url = $php_url . '../attached/';
// Define the file extensions allowed to upload
$ext_arr = array(
'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
'flash' => array('swf', 'flv'),
'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'txt', 'zip', 'rar', 'gz', 'bz2'),
);
// Maximum file size
$max_size = 1000000;
$save_path = realpath($save_path) . '/';
//PHP Upload failed
if (!empty($_FILES['imgFile']['error'])) {
switch($_FILES['imgFile']['error']){
case '1':
$error = ' exceed php.ini Allowed size .';
break;
case '2':
$error = ' Exceeds the allowed size of the form .';
break;
case '3':
$error = ' Only part of the picture was uploaded .';
break;
case '4':
$error = ' Please choose a picture .';
break;
case '6':
$error = ' Cannot find temporary directory .';
break;
case '7':
$error = ' Error writing file to hard disk .';
break;
case '8':
$error = 'File upload stopped by extension.';
break;
case '999':
default:
$error = ' Unknown error .';
}
$this->alert($error,$json);
}
// When uploading files
if (empty($_FILES) === false) {
// original file name
$file_name = $_FILES['imgFile']['name'];
// Temporary file name on the server
$tmp_name = $_FILES['imgFile']['tmp_name'];
// file size
$file_size = $_FILES['imgFile']['size'];
// check filenames
if (!$file_name) {
$this->alert(" Please select a file .",$json);
}
// check directories
if (@is_dir($save_path) === false) {
$this->alert(" Upload directory does not exist .",$json);
}
// Check directory write permissions
if (@is_writable($save_path) === false) {
$this->alert(" Upload directory does not have write permission .",$json);
}
// Check whether it has been uploaded
if (@is_uploaded_file($tmp_name) === false) {
$this->alert(" Upload failed .",$json);
}
// Check file size
if ($file_size > $max_size) {
$this->alert(" Upload file size exceeds limit .",$json);
}
// Check the directory name
$dir_name = empty($_GET['dir']) ? 'image' : trim($_GET['dir']);
if (empty($ext_arr[$dir_name])) {
$this->alert(" The directory name is incorrect .",$json);
}
// Get file extension
$temp_arr = explode(".", $file_name);
$file_ext = array_pop($temp_arr);
$file_ext = trim($file_ext);
$file_ext = strtolower($file_ext);
// Check extension
if (in_array($file_ext, $ext_arr[$dir_name]) === false) {
$this->alert(" Upload file extension is not allowed .\n Only " . implode(",", $ext_arr[$dir_name]) . " Format .",$json);
}
// Create folder
if ($dir_name !== '') {
$save_path .= $dir_name . "/";
$save_url .= $dir_name . "/";
if (!file_exists($save_path)) {
mkdir($save_path);
}
}
$ymd = date("Ymd");
$save_path .= $ymd . "/";
$save_url .= $ymd . "/";
if (!file_exists($save_path)) {
mkdir($save_path);
}
// New file name
$new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
// Moving files
$file_path = $save_path . $new_file_name;
if (move_uploaded_file($tmp_name, $file_path) === false) {
$this->alert(" Failed to upload file .",$json);
}
@chmod($file_path, 0644);
$file_url = $save_url . $new_file_name;
header('Content-type: text/html; charset=UTF-8');
echo $json->encode(array('error' => 0, 'url' => $file_url));
exit;
}
}
public function alert($msg,$json) {
header('Content-type: text/html; charset=UTF-8');
echo $json->encode(array('error' => 1, 'message' => $msg));
exit;
}
}
Be accomplished !!!
边栏推荐
- Nailing open platform - applet development practice (nailing applet client)
- Install cenos in the virtual machine
- Ubuntu installs PostgreSQL and uses omnidb to view
- Realize video call and interactive live broadcast in the applet
- 钉钉开放平台-小程序开发实战(钉钉小程序服务器端)
- List of provinces, cities and counties in China
- ctf [RoarCTF 2019]easy_ calc
- Verrouillage de lecture et d'écriture pour la synchronisation des fils
- Your requirements could not be resolved
- win10 系统打开的软件太小,如何变大(亲测有效)
猜你喜欢

Minecraft 1.16.5 生化8 模组 1.9版本 1.18版本同步

The open software of win10 system is too small. How to make it larger (effective through personal test)

Sorting out the examination sites of the 13th Blue Bridge Cup single chip microcomputer objective questions

Swagger

Threejs special sky box materials, five kinds of sky box materials are downloaded for free

35 year old programmer fired Luna millions of assets and returned to zero in three days. Netizen: it's the same as gambling

Nailing open platform - applet development practice (nailing applet client)

Using jsup to extract images from interfaces

Unity mobile game performance optimization spectrum CPU time-consuming optimization divided by engine modules

Sixtool- source code of multi-functional and all in one generation hanging assistant
随机推荐
Resolve PHP is not an internal or external command
go语言泛型在IDE中语法报错
Mobile terminal pull-down loading pull-down loading data
[learn FPGA programming from scratch -45]: vision chapter - integrated circuits help high-quality development in the digital era -2- market forecast
Knowledge of functions
An unexpected attempt (Imperial CMS list template filters spaces and newlines in smalltext introduction)
Svn correlation
Navicat connects the pit of shardingsphere sub table and sub library plug-ins
線程同步之讀寫鎖
35岁程序员炒Luna 千万资产3天归零,网友:和赌博一样
What if the serial port fails to open when the SCM uses stc-isp to download software?
SQL related knowledge - constraints
Mysql8.0 configuring my SQL in INI file_ mode=NO_ AUTO_ CREATE_ User can start
Review of number theory
Verrouillage de lecture et d'écriture pour la synchronisation des fils
Unity mobile game performance optimization spectrum CPU time-consuming optimization divided by engine modules
[Qunhui] this suite requires you to start PgSQL adapter service
How much do you make by writing a technical book? To tell you the truth, 2million is easy!
Go SQL parsing time Time type
Etcd watch principle