***JS***
<script>
function example_image_upload_handler (blobInfo, success, failure, progress) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', '/home/uplaodimage');
xhr.upload.onprogress = function (e) {
progress(e.loaded / e.total * 100);
};
xhr.onload = function() {
var json;
if (xhr.status === 403) {
failure('HTTP Error: ' + xhr.status, { remove: true });
return;
}
if (xhr.status < 200 || xhr.status >= 300) {
failure('HTTP Error: ' + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != 'string') {
failure('Invalid JSON: ' + xhr.responseText);
return;
}
success(json.location);
};
xhr.onerror = function () {
failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
};
</script>
<script>
tinymce.init({ selector:'textarea.editor',
image_title: true,
automatic_uploads: true,
file_picker_types: 'image',
images_upload_handler: example_image_upload_handler,
convert_urls: false,
</script>
PHP
$accepted_origins = array("http://localhost","https://yoursite.com");
$imageFolder = dirname(BASEPATH) . "/uploads/";
reset($_FILES);
$temp = current($_FILES);
if(is_uploaded_file($temp['tmp_name'])){
if(isset($_SERVER['HTTP_ORIGIN'])){
if(in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)){
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
}else{
header("HTTP/1.1 403 Origin Denied");
return;
}
}
if(preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])){
header("HTTP/1.1 400 Invalid file name.");
return;
}
if(!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))){
header("HTTP/1.1 400 Invalid extension.");
return;
}
$immage_name= $temp['name'];
$filetowrite = $imageFolder . $immage_name;
move_uploaded_file($temp['tmp_name'], $filetowrite);
echo json_encode(array('location' => '/uploads/'.$immage_name));
} else {
header("HTTP/1.1 500 Server Error");
}