CKEditor4结合php实现上传图片功能
To implement image uploading functionality in CKEditor 4 using PHP, you can follow these steps:
Install CKEditor 4: Download the CKEditor 4 library from the official website: https://ckeditor.com/ckeditor-5/download/
Create a CKEditor configuration file: Create a JavaScript file (e.g., config.js
) to configure CKEditor 4 and include the image upload plugin.
CKEDITOR.editorConfig = function(config) {
// Configure CKEditor settings
config.toolbar = [
['Source', 'NewPage', 'Save', 'Undo', 'Redo', 'Bold', 'Italic', '-', 'Link', 'Unlink', 'Image', 'Insert', 'MediaEmbed'],
];
// Enable image upload plugin
config.plugins = 'imageuploader';
// Configure image upload settings
config.imageUploader = {
// Set the URL for the PHP script to handle image uploads
uploadUrl: 'upload.php',
// Configure the allowed image formats
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
// Set maximum image file size (in bytes)
maximumFileSize: 1048576, // 1 MB
};
};
upload.php
) to handle image uploads and return the uploaded image URL to CKEditor.
<?php
// Check if a file was uploaded
if (isset($_FILES['upload']['error']) && $_FILES['upload']['error'] === UPLOAD_ERR_OK) {
// Get file information
$fileName = $_FILES['upload']['name'];
$fileTmpName = $_FILES['upload']['tmp_name'];
$fileSize = $_FILES['upload']['size'];
$fileType = $_FILES['upload']['type'];
$fileError = $_FILES['upload']['error'];
// Validate file extension
$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
$fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
if (!in_array($fileExtension, $allowedExtensions)) {
echo json_encode(['error' => 'Invalid file extension']);
exit;
}
// Validate file size
$maxFileSize = 1048576; // 1 MB
if ($fileSize > $maxFileSize) {
echo json_encode(['error' => 'File size exceeds maximum limit']);
exit;
}
// Generate unique file name
$newFileName = uniqid() . '.' . $fileExtension;
// Move uploaded file to a designated directory
$uploadDir = 'uploads/';
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0777, true);
}
$moveResult = move_uploaded_file($fileTmpName, $uploadDir . $newFileName);
if ($moveResult) {
// Image upload successful
$uploadedImageUrl = $uploadDir . $newFileName;
echo json_encode(['url' => $uploadedImageUrl]);
} else {
// Image upload failed
echo json_encode(['error' => 'Failed to upload file']);
}
} else {
// No file uploaded or upload error
echo json_encode(['error' => 'No file uploaded']);
}
<!DOCTYPE html>
<html>
<head>
<title>CKEditor Image Upload</title>
<script src="ckeditor/ckeditor.js"></script>
<script src="config.js"></script>
</head>
<body>
<textarea id="editor" rows="10" cols="80"></textarea>
<script>
// Replace the textarea with CKEditor instance
CKEDITOR.replace('editor');
</script>
</body>
</html>
With this setup, you should be able to upload images directly within the CKEditor editor and have the uploaded images inserted into the edited content.