当前位置:网站首页>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 !!!
边栏推荐
- CTF serialization and deserialization
- Review of number theory
- [Qunhui] command line acme SH automatically apply for domain name certificate
- Video label forbids downloading. The test is valid. Hide button. The test is valid at three points
- Force buckle 515 Find the maximum value in each tree row
- How to use EEPROM in 51 Single Chip Microcomputer?
- SixTool-多功能多合一代挂助手源码
- Install dbeaver and connect Clickhouse
- An unexpected attempt (Imperial CMS list template filters spaces and newlines in smalltext introduction)
- Analysis report on the development trend and operation status of China's environmental monitoring instrument industry from 2022 to 2028
猜你喜欢

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

Wechat applet is bound to a dynamic array to implement a custom radio box (after clicking the button, disable the button and enable other buttons)
![Laravel framework Alipay payment fails to receive asynchronous callback request [original]](/img/a7/139604ec3a977f2a4e96f392e56602.jpg)
Laravel framework Alipay payment fails to receive asynchronous callback request [original]

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

SQL related knowledge - DDL

Nailing open platform - applet development practice (nailing applet server side)

Sorting out the examination sites of the 13th Blue Bridge Cup single chip microcomputer objective questions
![Tp6 is easy to tread [original]](/img/e9/4b2fbd485387c5ed9e75bd0451a19c.jpg)
Tp6 is easy to tread [original]

08_SpingBoot 集成Redis

Install dbeaver and connect Clickhouse
随机推荐
Computer network high frequency interview questions
[QT] dialog box
Read / write lock for thread synchronization
Report on the "fourteenth five year plan" and future development direction of global and Chinese indoor vertical farms from 2022 to 2028
Threejs专用天空盒素材,五种天空盒素材免费下载
How to use EEPROM in 51 Single Chip Microcomputer?
VHDL design
[QT] resource file import
What if the serial port fails to open when the SCM uses stc-isp to download software?
线程同步之互斥量(互斥锁)
In 2022, what professional competitions can college students majoring in automation, electrical engineering and automation participate in?
Threejs special sky box materials, five kinds of sky box materials are downloaded for free
Report on operation mode and future development trend of China's refining and chemical market 2022-2028
Navicat connects the pit of shardingsphere sub table and sub library plug-ins
PHP inherited in class return does not work
Be a hard worker from today on
List of provinces, cities and counties in China
Report on demand situation and development trend of China's OTC industry from 2022 to 2028
PIP batch complete uninstall package
Parse JSON interface and insert it into the database in batch