Image upload from ckeditor to laravel local file system - javascript

Am trying to upload image using ckeditor to my local file system in laravel for which i made a code which is working fine image is uploading properly everything is working fine except in ckeditor it doesn't show link here is my code :
<script>
window.onload = function() {
CKEDITOR.replace('long_description', {
filebrowserUploadUrl: '{{ route('upload',['_token' => csrf_token() ]) }}'
});
};</script>
on the rote part i make a route for upload like this :
Route::post('upload_image','CkeditorController#uploadImage')->name('upload');
and in the controller part i use this code :
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class CkeditorController extends Controller
{
public function uploadImage(Request $request) {
$CKEditor = $request->input('CKEditor');
$funcNum = $request->input('CKEditorFuncNum');
$message = $url = '';
if (Input::hasFile('upload')) {
$file = Input::file('upload');
if ($file->isValid()) {
$filename =rand(1000,9999).$file->getClientOriginalName();
$file->move(public_path().'/wysiwyg/', $filename);
$url = url('wysiwyg/' . $filename);
} else {
$message = 'An error occurred while uploading the file.';
}
} else {
$message = 'No file uploaded.';
}
return '<script>window.parent.CKEDITOR.tools.callFunction('.$funcNum.', "'.$url.'", "'.$message.'")</script>';
}
}
when i try to upload upload is working fine image goes in dir but in respose i got error :
[CKEDITOR] Error code: filetools-response-error. {responseText: "<script>window.parent.CKEDITOR.tools.callFunction(…linic/wysiwyg/4121dominospizza.jpg", "")</script>"}
so i search for error but i didn't get it the error description was
An error occurred when parsing the upload response. Text could not be parsed to JSON.
Additional data:
responseText: Upload response text.
help me out please thanks in advance.

Related

Image Download Issue with jquery plugin and php stuff

I have created a QR code generating website. QR code is generated through PHP QR code generator library
by using this code
include_once "../phpqrcode/qrlib.php";
$PNG_TEMP_DIR = '../qrcodeImages/';
if (isset($_REQUEST['text'])) {
$content = $_REQUEST['text'];
$filename = $PNG_TEMP_DIR . 'qr' . md5($content) . '.png';
QRcode::png($content, $filename, 10);
echo $image = "<img class='img' src='qrcodeImages/" . basename($filename) . "'/>";
// $image_src = "qrcodeImage/" . basename($filename);
};
with this ajax call i append the QR code in the required div
$.ajax({
url: "code/single_input_to_qrcode.php",
type: "POST",
data: { text: jquery_plain_text },
success: (parms) => {
$("#downloadPart_img img").remove();
$("#downloadPart_img").append(parms);
}
});
and under QR code div I have placed a download button which is used to download the QR code
for downloading purpose I have used JavaScript library "File Saver"
code
var url = $("#downloadPart_img img").attr('src');
if (url == "img/white-qr-code.png") {
$("#error_msg_div").animate({ "top": "20px" });
error_msg = "Please generate a QR code before download";
error_msg_div.html(error_msg);
} else {
var file_name = url.substring(url.lastIndexOf('/') + 1);
url = "localhost/qrCodeGenerator/" + url;
saveAs(url, file_name);
}
But when user hit download button it show failed to download what kind of issue is that. I thinks this is because when the user hit the download button at the same time the file is saving in the folder so file is not available their at that time.
I have search a lot about that but I am fail to get its solution so now I am on this site to find solution so if some one now how to fix this problem so please help me.
Advance thanks
image of website and failed file at left bottom

When including session I can not use $_FILES

I am uploading a csv file and sending it to page to process using the js fetch api. I have session included using my init file and all works well accept for the page that should process to file info. Without including the session it works fine and I can process the file, when including it, I can see al the session info, but $_FILES just stops working, I can't see any of the info for some reason.
I really hope this is something stupid
Some code if needed
The init file
<?php
//define Site Root and Includes Path
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
defined('SITE_ROOT') ? null : define('SITE_ROOT', __DIR__ . DS );
defined('INCLUDES_PATH') ? null : define('INCLUDES_PATH', SITE_ROOT);
//get class files
include(INCLUDES_PATH.DS."Session.php");
require_once(INCLUDES_PATH.DS."functions.php");
require_once(INCLUDES_PATH.DS."DB.php");
require_once(INCLUDES_PATH.DS."Validation.php");
require_once(INCLUDES_PATH.DS."User.php");
require_once(INCLUDES_PATH.DS."Swp.php");
require_once(INCLUDES_PATH.DS."Incident.php");
require_once(INCLUDES_PATH.DS."Hira.php");
require_once(INCLUDES_PATH.DS."Mail.php");
The Session.php page
<?php
class Session
{
private $logged_in;
public $user_id;
function __construct()
{
session_start();
$this->check_login();
}
public function is_logged_in() {
return $this->logged_in;
}
private function check_login() {
if (isset($_SESSION['UserID'])) {
$this->user_id = $_SESSION['UserID'];
$this->logged_in = true;
} else {
unset($this->user_id);
$this->logged_in = false;
}
}
}
$session = new Session();
The form page
<?php
//get all the includes
require_once("../php_functions/_init.php");
print_r($_FILES);
//all rows from csv file
$rows = array_map('str_getcsv', file($_FILES['file']['tmp_name'][0]));
//get only the headers
$header = array_shift($rows);
//declare the array
$csv = array();
//create associative array using array_combine
foreach ($rows as $row) {
$csv[] = array_combine($header, $row);
}
print_r($csv);
like I mentioned if I removed the require once from this page it works as expected. Any ideas would help
Just in case you need it here is the js for uploading the file
document.querySelector("#upload_file").addEventListener("click", function () {
const url = 'php/employee/upload_employee_csv_form.php';
const files = document.querySelector('[type=file]').files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('file[]', file);
}
console.log(formData);
fetch(url, {
method: 'POST',
body: formData
}).then(response => {
console.log(response);
});
});
I actually figured it out. So my session was being included before I actually added it, to fix this instead of just saying session_start I check to see if the session is there and then only start if necessary.
The code
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
Bonus tip :-)
The above code will work for php 5.4 and up if you are running something lower than 5.4 you can do the following:
if(session_id() == '') {
session_start();
}
Hope this helps

How do I run a .php function file from a .js file

How do I send data from a JavaScript file to a PHP file so that it does what it needs to do in the PHP server side. I want to send a SMS and my JavaScript is reading all the data that is coming though so all that is left is that my PHP activates and sends the data in a SMS which is already done with my PHP file. I just need to make them connect to be able to send.
Can PHP handle functions? That is what I am trying to do here by sending the data to a function in PHP from my .js file. If not, how do I send them via post?
.js file:
render : function(template,params){
var arr = [];
switch(template){
case 'smsLine':
arr = [
'<div class=" sms-',params.id,' rounded"><span class="gravatar"><img src="',params.gravatar,
'" width="23" height="23" onload="this.style.visibility=\'visible\'" />',
'</span><span class="author">',params.author,
':</span><span class="text">',params.text,
':</span><span class="text">',params.to,
'</span><span class="time">',params.time,'</span></div>'];
///////////////////////////////HERE/////////////////////////////////
//this is where I want to use a function that is in a php file
sendSMS(params.author, params.text, params.time, params.to);
///////////////////////////////HERE////////////////////////////////
break;
}
return arr.join('');
}
This is the function that I want to use in my PHP file.
.php file:
function sendSMS($from, $message, $time, $to){
$objGsm = new COM("AxSms.Gsm", NULL, CP_UTF8 );
$objGsm->LogFile = sys_get_temp_dir()."Gsm.log";
//Windows default: 'C:\Windows\Temp\Gsm.log'
//Form submitted
$obj;
$strMessageReference;
$objSmsMessage = new COM("AxSms.Message", NULL, CP_UTF8 );
$objSmsConstants = new COM("AxSms.Constants" , NULL, CP_UTF8 );
$strName = 'Modem';
$strPincode = '';
$strRecipient = '$number';
$iDeviceSpeed = '0';
$objGsm->Clear();
$objGsm->LogFile = '';
$objGsm->Open($strName, $strPincode, $iDeviceSpeed);
if ($objGsm->LastError != 0){
$strResult = $objGsm->LastError . ": " . $objGsm->GetErrorDescription($objGsm->LastError);
$objGsm->Close();
}
else{
//Message Settings
$objSmsMessage->Clear();
$objSmsMessage->ToAddress = $to;
$objSmsMessage->Body = $message;
$objSmsMessage->DataCoding = $objSmsConstants->DATACODING_UNICODE;
//Send the message !
$obj = $objSmsMessage;
$objGsm->SendSms($obj, $objSmsConstants->MULTIPART_ACCEPT, 0);
$objSmsMessage = $obj;
$strResult = $objGsm->LastError . ": " . $objGsm->GetErrorDescription($objGsm->LastError);
$objGsm->Close();
}
}
If you pull in jQuery to your front-end, you'll be able to send an AJAX request to execute that PHP function for you. it would look something like this (inserted straight into that sendSMS section in the .js code:
$.ajax() {
url: "/send/sms",
type: "POST",
data: {
author: params.author,
text: params.text,
time: params.time,
to: params.to,
}
}
Now what you will have to do is create the file for the AJAX request to be sent to, they call this an "end point". In my example I set the path of this file to being /send/sms, so perhaps you have a directory called "send" where you could send off an email or SMS, etc. For each of those methods you would have a PHP file containing the logic for it. So for this example, create an sms.php file inside YOUR_ROOT_DIRECTORY/send .
Once you send an AJAX request to that file, the PHP function will be executed. To fetch the given data, use $_POST['author'], $_POST['text'], etc.

Cant upload files from mobile version to classic version directory, same domain

im currently having an issue with the upload of files from the mobile version of the site im currently working with, I think the issue is related to the fact that the mobile version files are outside the public_hmtl folder inside a folder named m, this was done like this because the m.site.com link wouldnt work otherwise, since im using the classic site folder to store all the media, the problem starts here:
heres the path im working with:
/
/m
/public_html
the file in
/m/user/fnc/upload.php
is directed to save an img to
/public_html/photos/users/
here's a fragment of the code in upload.php
for the first line, I use a redirect variable called $img that leads to the index of the classic version, that would be
www.mysite.com/
so
$URL = $img.'photos/users/';
$NewFotoName = "misite_".$usuarioid."_".time().".jpg";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$imagen = $_POST['Imagen'];
if ( isset($_POST['Imagen']) ) {
$image = base64_decode($imagen);
$im = imagecreatefromstring($image);
imagepng($im,$URL.$NewFotoName);
imagedestroy($im);
$query = "UPDATE Utenti SET foto = '$NewFotoName' WHERE id_utente = ".$usuarioid;
$result = $mysqli->query($query);
if(!$result){die($mysqli->error);}
echo "index2.php";
die();
} else {
echo "index2.php";
die();
}
} else {
echo "index2.php";
die();
}
and i call it from a file one folder above it called index2.php with this code:
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'original'
}).then(function (resp) {
$('#imagebase64').val(resp);
var imagen_cortada = $('#imagebase64').val();
var base64image = imagen_cortada;
var parametros = { "Imagen" : base64image };
$.ajax({
data: { "Imagen" : output },
url: 'fnc/upload.php',
method: 'POST', // or GET
success: function(msg)
{
alert("Imagen subida con exito.");
alert(msg);
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("Error al Subir la Imagen.");
alert(errorThrown);
window.location.replace(msg);
}
});
now when the form is submited I get a succes alert but in the "alert(msg);" I get an error that says
imagepng(path/to/the/file.png): failed to open stream; no such file or
directory in /home/mysite/m/user/fnc/upload.php
So the name of the file gets saved into the database but the file doesnt.
I appreciate any suggestions, excuse any spelling mistakes.
//edit
I found a work arround and moved the subdomaind directory inside public_html, had to learn a bit about the .htacces, it seems this way i will not have all those pesky permision problems
I found a work arround and moved the subdomaind directory inside public_html, had to learn a bit about the .htacces, it seems this way i will not have all those pesky permision problems, the other workarrounds posted in the similar thread Vic Seedoubleyew posted didnt seem to do the trick for me

How to store image to folder and store the path to database using Ajax?

I am developing an application that use HTML and js for front-end and PHP for back-end. I have the following code which should have the functions that: 1, when click on the background image, user can choose photo from there phone as new background image, and use PHP to save the image on server and get the image path, store the path into database, then send new path back to front with JSON, and display the selected image as new background image. Thanks for any help.
javascript for sending and retrieve data:
function UploadImageDialog()
{
$("#newProfileImage").click();
}
function profileImageSelected(fileInput)
{
var xhr = new XMLHttpRequest();
xhr.open("POST", "UploadProfileImage.php", true);
var formData = new FormData();
formData.append("file", fileInput.files[0]);
xhr.send(formData);
xhr.onload = function() {
alert(xhr.responseText); //test the returned info from PHP.
if(xhr.responseText != ""){
$("#profileBackgroundImage").setAttribute("src", xhr.responseText);
}
else
{
alert("Your file failed to upload");
}
}
}
HTML code to call the javascript:
<div style="width:91.5vw;height:78.5vh;margin-top:10.5vh;">
<img class="backgroundImage" id="pictureSrc" src="img/Jenny.jpg" onclick="UploadImageDialog()" />
</div>
<input type="file" id="newProfileImage" style="display:none;" onchange="profileImageSelected(this)"/>
PHP code to get the path:
<?php
if(is_uploaded_file($_FILES['file']['tmp_name'])) // if user uploads file
{
if (!file_exists("./img/EventImages/" . $_FILES["file"]["name"]))
{
if (move_uploaded_file($_FILES["file"]["tmp_name"], "./img/EventImages/" . $_FILES["file"]["name"]))
{
echo "img/EventImages/" . $_FILES["file"]["name"];
}
}
else
{
echo "img/EventImages/" . $_FILES["file"]["name"];
}
}
?>
You should use some libraries like uploadify to upload files without posting form.
DEMO
I have figured that out. There was nothing wrong with the code, but I didn't set the Directory Permission correctly on the server.

Categories

Resources