Skip to content

Instantly share code, notes, and snippets.

@jonathanMelly
Created November 19, 2021 13:14
Show Gist options
  • Save jonathanMelly/e972b00ee4f5004448b00b133171b191 to your computer and use it in GitHub Desktop.
Save jonathanMelly/e972b00ee4f5004448b00b133171b191 to your computer and use it in GitHub Desktop.
ckeditor image upload php backend
<?php
//ck editor config
//config.extraPlugins = 'uploadimage';
//config.imageUploadUrl='/upload/upload.php';
$maxSizeInMo=50;
$csrfName = "ckCsrfToken";
$token = $_POST[$csrfName];
$uploadKey = "upload";
$targetDir = "data/";
//Security check
if($token == $_COOKIE[$csrfName] && isset($_FILES[$uploadKey]))
{
$tmpPath = $_FILES[$uploadKey]["tmp_name"];
//Format check
if(getimagesize($tmpPath)!==false)
{
$tmpName = basename($tmpPath);
$nameWithExtension = basename($_FILES[$uploadKey]["name"]);
//$extension = strtolower(pathinfo($nameWithExtension,PATHINFO_EXTENSION));
$targetName = $tmpName . "-" .$nameWithExtension;
$targetPath = dirname(__FILE__) . "/" . $targetDir . $targetName;
// Check file size
if ($_FILES[$uploadKey]["size"] > (1024*1024*$maxSizeInMo))
{
error("Sorry, your file is too large (max=".$maxSizeInMo .")");
}
//Should never happen (tmp_name is unique)
else if(file_exists($targetPath))
{
error("Sorry, file already exists.");
}
else
{
$targetType = $_FILES[$uploadKey]["type"];
//
// Allow certain file formats
if($targetType != "image/jpg" && $targetType != "image/png" && $targetType != "image/jpeg" && $targetType != "image/gif" && $targetType != "image/bmp" )
{
error("Sorry, only JPG, JPEG, PNG & GIF & BMP files are allowed.");
}
else
{
if (move_uploaded_file($tmpPath, $targetPath)) {
//echo "The file ". htmlspecialchars($targetPath). " has been uploaded.";
$url = "/" . basename(dirname(__FILE__)) . "/" . $targetDir . $targetName;
$json["uploaded"] = true;
$json["url"] = $url;
echo json_encode($json);
} else {
error("Sorry, there was an error uploading your file.");
}
}
}
}
}
function error($message)
{
$json["uploaded"] = false;
$json["error"] = array("message" => $message);
echo json_encode($json);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment