I used ckeditor 5 zip in my laravel project. but it was not working when I add image upload plugin from ckeditor cloudServices.
Here is the documentation
https://ckeditor.com/docs/ckeditor5/latest/features/image-upload/image-upload.html
my html code in blade.
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" name="description" id="description"
rows="3">{{ old('description') }}</textarea>
</div>
here is my script
<script>
ClassicEditor
.create(document.querySelector('#description'), {
cloudServices: {
tokenUrl: '{{ csrf_token() }}',
uploadUrl: '{{ public_path('../../img/desc-img') }}'
}
})
.then(editor => {
window.editor = editor;
})
.catch(err => {
console.error(err.stack);
});
</script>
define your textarea
<textarea class="form-control" id="ckeditor" name="ckeditor"></textarea>
and instantiate the ckeditor using this code.
CKEDITOR.replace('ckeditor ', {
filebrowserUploadUrl: "{{route('ckeditor.image-upload', ['_token' => csrf_token() ])}}",
filebrowserUploadMethod: 'form'
});
then create the action for uploading images and define your route like so:
/**
* upload images from ckeditor.
*
* #param Request $request
* #return \Illuminate\Http\Response
*/
public function upload_images(Request $request)
{
$request->validate([
'upload' => 'image',
]);
if ($request->hasFile('upload')) {
$url = $request->upload->store('images');
$CKEditorFuncNum = $request->input('CKEditorFuncNum');
$url = asset('storage/' . $url);
$msg = 'Image successfully uploaded';
$response = "<script>window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')</script>";
#header('Content-type: text/html; charset=utf-8');
return $response;
}
}
And that is it.
use these script to call Ckeditor
<script src="https://cdn.ckeditor.com/ckeditor5/22.0.0/classic/ckeditor.js"></script>
<script type="text/javascript">
CKEDITOR.replace('editor1', {
filebrowserUploadUrl: "{{route('ckeditor.upload', ['_token' => csrf_token() ])}}",
filebrowserUploadMethod: 'form'
});
</script>
and after put these code in your imageUploaderController
if($request->hasFile('upload')) {
$originName = $request->file('upload')->getClientOriginalName();
$fileName = pathinfo($originName, PATHINFO_FILENAME);
$extension = $request->file('upload')->getClientOriginalExtension();
$fileName = $fileName.'_'.time().'.'.$extension;
$request->file('upload')->move(public_path('images'), $fileName);
$CKEditorFuncNum = $request->input('CKEditorFuncNum');
$url = asset('images/'.$fileName);
$msg = 'Image uploaded successfully';
$response = "<script>window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')</script>";
#header('Content-type: text/html; charset=utf-8');
echo $response;
}
It works for me, try it.
And don't forget to stop script execution with exit.
if ($request->hasFile('upload')) {
//some code for uploading
echo $response;
exit;
}
Related
Trying to implement a comments system using pusher on my laravel project. Everything seems to be in order, however every post request which is meant to send the input data to the database returns with error 500.
Used F12 on firefox to monitor what gets sent to /tip/select, it seems that it passes the text of the comment just fine, so it could be the issue with the controller.
Routes
Route::get('/tip/select','TipController#select');
Route::post('/tip/select', 'TipController#addComment');
Comment model
namespace App;
use Illuminate\Database\Eloquent\Model;
use Zttp\Zttp;
use App\model\User;
use App\Tip;
class Comment extends Model
{
protected $guarded = [];
protected $table='comments';
//protected $fillable=['tip_id','user_id','body'];
public static function moderate($comment)
{
$response = Zttp::withoutVerifying()->post("https://commentator.now.sh", [
'comment' => $comment,
'limit' => -3,
])->json();
if ($response['commentate']) {
abort(400, "Comment not allowed");
}
}
public function tip(){
return $this->belongsTo('App\Tip');
}
public function user(){
return $this->belongsTo('App\model\User');
}
}
Controller
use Pusher\Laravel\Facades\Pusher;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Input;
use DB;
use Image;
use App\Tip;
use App\model\User;
use App\Subcategories;
use App\Category;
use App\City;
use App\Comment;
use App\CityAreas;
//use App\Http\Requests\TipFormRequest;
class TipController extends Controller
{
public function select(){
//$db=DB::table('tips')->orderBy('created_at','desc');
$data=Tip::get();
$url = Storage::disk('s3');
//$data=Tip::paginate(10);
//$data=$db->get();
// dd($data);
$comments = Comment::orderBy('id')->get();
return view('tip', compact('data', 'url','comments'));
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function create(){
$categories=Category::all();
$cities=City::all();
return view('tip.create',compact('categories','cities'));
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function store(Request $request, City $city, Category $category){
$this->validate($request, [
'image' => 'image|nullable|max:1999']);
$tipsnew = new Tip;
$tipsnew->title = $request->title;
$tipsnew->description = $request->description;
$tipsnew->category_id = $request->category;
$tipsnew->city_id = $request->city;
$tipsnew->user_id = auth()->id();
$tipsnew->url = $request->url;
if ($request->hasFile('image')) {
try{
$file = $request->file('image');
$name = time() . '.' . $file->getClientOriginalExtension();
$img = \Image::make($file->getRealPath());
$img->fit(1080);
$img->stream();
Storage::disk('s3')->put('tip'.'/'.$name, $img->__toString());
$tipsnew->image = 'tip'.'/'.$name;
}
catch (\Exception $e)
{
$response = [
'information' => 'Error. Something went wrong. Please try again',
];
$statusCode = 400;
return response()->json($response, $statusCode);
}
}
$tipsnew->save();
return redirect ('tip/create')->with('status','your tip is created');
}
public function edit($id){
$tip=Tip::whereId($id)->firstOrFail();
$categories=Category::all();
$selectedCategories=$tip->categories->lists('id')->toArray();
return view('tip.edit',compact('tip','categories','selectedCategories'));
}
public function search(Request $request, City $city, Category $category, User $user){
$q = $request->get('q');
if ($q != ""){
$tips = Tip::where('title','LIKE','%'.$q.'%')
->orWhere('description','LIKE','%'.$q.'%')
->orWhereHas('user', function($id) use($q){
return $id->where('name', 'LIKE','%'.$q.'%');
})
->orWhereHas('city', function($id) use($q){
return $id->where('name', 'LIKE','%'.$q.'%');
})
->orWhereHas('category', function($id) use($q){
return $id->where('name', 'LIKE','%'.$q.'%');
})
->get();
if(count($tips) > 0)
return view('tip.search', ['tips' => $tips]);
}
}
public function addComment(Request $request)
{
$data = $request;
Comment::moderate($data['text']);
$comment = Comment::create($data);
Pusher::trigger('comments', 'new-comment', $comment, request()->header('X-Socket-Id'));
//add creation of new comment to DB
$commentnew = new Comment;
$commentnew->user_id = Auth::user()->id();
//$commentnew->tip_id= $request->post(['tip_id']);
$commentnew->body = $request->text;
$commentnew->save();
return $comment;
}
}
Snippet of the blade
<h3>Comments</h3>
<form onsubmit="addComment(event);">
<input type="text" placeholder="Add a comment" name="text" id="text" required>
<input type="hidden" name="tip_id" id="tip_id" value="{{$val->tip_id}}">
<input type="hidden" name="username" id="username" value="{{Auth::user()->name}}">
<button id="addCommentBtn">Comment</button>
</form>
<div class="alert" id="alert" style="display: none;"></div>
<br>
<div id="comments">
#foreach($comments as $comment)
<div>
<small>{{ $comment->username }}</small>
<br>
{{ $comment->text }}
</div>
#endforeach
</div>
<!--jQuery script used to be here -->
<script>
function displayComment(data) {
let $comment = $('<div>').text(data['text']).prepend($('<small>').html(data['username'] + "<br>"));
$('#comments').prepend($comment);
}
function addComment(event) {
function showAlert(message) {
let $alert = $('#alert');
$alert.text(message).show();
setTimeout(() => $alert.hide(), 4000);
}
event.preventDefault();
$('#addCommentBtn').attr('disabled', 'disabled');
var data = {
text: $('#text').val(),
username: $('#username').val(),
tipid: $('#tip_id').val(),
};
fetch('/tip/select', {
body: JSON.stringify(data),
credentials: 'same-origin',
headers: {
'content-type': 'application/json',
'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
'x-socket-id': window.socketId
},
method: 'POST',
mode: 'cors',
}).then(response => {
$('#addCommentBtn').removeAttr('disabled');
displayComment(data);
showAlert('Comment posted!');
})
}
</script>
I have used dropzone js to upload multiple image.
My code looks like below.
var s_currency = $('select[name="currency"]');
Dropzone.autoDiscover = false;
if($('#dropzoneDragArea').length > 0){
var expenseDropzone = new Dropzone("#expense-form", {
autoProcessQueue: false,
clickable: '#dropzoneDragArea',
acceptedFiles:allowed_files,
previewsContainer: '.dropzone-previews',
addRemoveLinks: true,
//maxFiles: 1,
//parallelUploads: 1,
uploadMultiple: true,
dictDefaultMessage:drop_files_here_to_upload,
dictFallbackMessage:browser_not_support_drag_and_drop,
dictRemoveFile:remove_file,
dictMaxFilesExceeded:you_can_not_upload_any_more_files,
error:function(file,response){
alert_float('danger',response);
},
success:function(file,response){
response = $.parseJSON(response);
this.options.autoProcessQueue = true;
if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
window.location.assign(response.url);
}
},
});
}
$(document).ready(function(){
_validate_form($('form'),{category:'required',date:'required',amount:'required',currency:'required'},expenseSubmitHandler);
$('input[name="billable"]').on('change',function(){
do_billable_checkbox();
});
});
function expenseSubmitHandler(form){
s_currency.removeAttr('disabled');
$('input[name="billable"]').prop('disabled',false);
$.post(form.action, $(form).serialize()).success(function(response) {
response = $.parseJSON(response);
if (response.expenseid) {
if(typeof(expenseDropzone) !== 'undefined'){
//console.log(expenseDropzone.getQueuedFiles().length);return;
if (expenseDropzone.getQueuedFiles().length > 0) {
expenseDropzone.options.url = admin_url + 'expenses/add_expense_attachment/' + response.expenseid;
expenseDropzone.processQueue();
} else {
window.location.assign(response.url);
}
} else {
window.location.assign(response.url);
}
} else {
window.location.assign(response.url);
}
});
return false;
}
<form action="http://127.0.0.1/perfex_crm_aug_25/admin/expenses/expense" id="expense-form" class="dropzone dropzone-manual" enctype="multipart/form-data" method="post" accept-charset="utf-8" novalidate="novalidate">
<div id="dropzoneDragArea" class="dz-default dz-message">
<span>Attach file here</span>
</div>
<div class="dropzone-previews"></div>
<button type="submit" class="btn btn-info pull-right mtop15">Submit</button>
</form>
My controler looks like this :
public function expense($id = '')
{
if (!has_permission('expenses', '', 'view')) {
access_denied('expenses');
}
if ($this->input->post()) {
if ($id == '') {
if (!has_permission('expenses', '', 'create')) {
set_alert('danger', _l('access_denied'));
echo json_encode(array(
'url' => admin_url('expenses/expense')
));
die;
}
$id = $this->expenses_model->add($this->input->post());
if ($id) {
set_alert('success', _l('added_successfuly', _l('expense')));
echo json_encode(array(
'url' => admin_url('expenses/list_expenses/' . $id),
'expenseid' => $id
));
die;
}
echo json_encode(array(
'url' => admin_url('expenses/expense')
));
die;
} else {
if (!has_permission('expenses', '', 'edit')) {
set_alert('danger', _l('access_denied'));
echo json_encode(array(
'url' => admin_url('expenses/expense/' . $id)
));
die;
}
$success = $this->expenses_model->update($this->input->post(), $id);
if ($success) {
set_alert('success', _l('updated_successfuly', _l('expense')));
}
echo json_encode(array(
'url' => admin_url('expenses/list_expenses/' . $id),
'expenseid' => $id
));
die;
}
}
if ($id == '') {
$title = _l('add_new', _l('expense_lowercase'));
} else {
$data['expense'] = $this->expenses_model->get($id);
$title = _l('edit', _l('expense_lowercase'));
//echo "<pre>";
//print_r($data['expense']);
}
if($this->input->get('customer_id')){
$data['customer_id'] = $this->input->get('customer_id');
$data['do_not_auto_toggle'] = true;
}
$this->load->model('taxes_model');
$this->load->model('payment_modes_model');
$this->load->model('currencies_model');
$this->load->model('projects_model');
$data['customers'] = $this->clients_model->get();
$data['taxes'] = $this->taxes_model->get();
$data['categories'] = $this->expenses_model->get_category();
$data['supplier'] = $this->expenses_model->get_supplier();
//print_r($data['supplier']);
$data['payment_modes'] = $this->payment_modes_model->get();
$data['currencies'] = $this->currencies_model->get();
$data['title'] = $title;
$this->load->view('admin/expenses/expense', $data);
}
I have also created helper for uploading image. That function looks like below :
function handle_lead_attachments($leadid)
{
if(isset($_FILES['file']) && _perfex_upload_error($_FILES['file']['error'])){
header('HTTP/1.0 400 Bad error');
echo _perfex_upload_error($_FILES['file']['error']);
die;
}
$CI =& get_instance();
if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
do_action('before_upload_lead_attachment',$leadid);
$path = LEAD_ATTACHMENTS_FOLDER . $leadid . '/';
// Get the temp file path
$tmpFilePath = $_FILES['file']['tmp_name'];
// Make sure we have a filepath
if (!empty($tmpFilePath) && $tmpFilePath != '') {
// Setup our new file path
if (!file_exists($path)) {
mkdir($path);
fopen($path . 'index.html', 'w');
}
$filename = unique_filename($path, $_FILES["file"]["name"]);
$newFilePath = $path . $filename;
// Upload the file into the company uploads dir
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
$CI =& get_instance();
$CI->db->insert('tblleadattachments', array(
'leadid' => $leadid,
'file_name' => $filename,
'filetype' => $_FILES["file"]["type"],
'addedfrom' => get_staff_user_id(),
'dateadded' => date('Y-m-d H:i:s')
));
$CI->load->model('leads_model');
$CI->leads_model->log_lead_activity($leadid, 'not_lead_activity_added_attachment');
return true;
}
}
}
return false;
}
Here, when I have upload one image than its working fine.But when I have tried to upload multiple image than it store other data image column has pass null value.
So what should I have to change in My code to upload multiple image. I have used perfex-crm project. I have to modify its expence module.
I'm trying to make a "meal" in my DB, so in my website i made a form with a name, and a picture. This is the code of the form :
<?php
$new_meal_title = htmlentities($_POST["new_meal_title"]);
$new_meal_img = htmlentities($_POST["new_meal_img"]);
$data = array(
'new_meal_title' => $new_meal_title,
'new_meal_img' => base64_encode($new_meal_img)
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents(constant("API_URL")."/meal", false, $context);
if($result === FALSE){
var_dump($result);
}
$json = json_decode($result);
if($json->success == "true"){
header('Location: ../../');
return;
}
else{
echo $json->message;
}
header('Location: ../../');
?>
The form is sending data to my Node API. My Question is, how to save into a folder the image path through form in Javascript after it has been received in JSON.
Thanks for your help, i just had to change this line :
$new_meal_img = htmlentities($_POST["new_meal_img"]);
By
$new_meal_img = $_FILES['new_meal_img']["tmp_name"];
And
'new_meal_img' => base64_encode($new_meal_img)
By
'new_meal_img' => base64_encode(file_get_contents($new_meal_img))
So i just found out about the jquery auto complete and i would like to add it to my web-page. I want to hook it up to my php code so i can search my sql database. However Whenever i try to run my auto complete,it doesnt seem to find the php array im passing ( im just trying to get an array to work for now) . Can someone help?
Jquery Code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#tags" ).autocomplete({
source: "test.php"
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
PHP code
<?php
$data[] = array(
'c++','Java','JavScript',"c#" );
echo json_encode($data);
?>
This is an updated version of your answer which should resolve the deprecated SQL driver and the injection issue. You need to replace the SECOND_COLUMNNAME with your actual column's name. Aside from that I think this should work.
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=DB','username','password');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
if(empty($_REQUEST['term']))
exit();
//require_once('connect.php'); connection to db is in this file so connection is not needed
$query = 'SELECT name, SECOND_COLUMNNAME FROM locations
WHERE name
LIKE ?
ORDER BY id ASC
LIMIT 0,10';
$stmt = $dbh->prepare($query);
$stmt->execute(array(ucfirst($_REQUEST['term']) . '%'));
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = array(
'label' => $row['name'],
'value' => $row['SECOND_COLUMNNAME']
);
}
echo json_encode($data);
flush();
Links:
http://php.net/manual/en/pdo.prepared-statements.php
http://php.net/manual/en/pdo.connections.php
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
How can I prevent SQL injection in PHP?
Also not sure if there was anything else inside connect.php, you might need to bring that back.
The array pattern used here should be as below.
<?php
$data = array(
array("value"=>'C++'),
array("value"=>'Java'),
array("value"=>'Javascript'),
array("value"=>'C#'),
);
echo json_encode($data);
If you're using PHP >= 5.4:
$data = [
[ 'value' => 'C++' ],
[ 'value' => 'Java' ],
[ 'value' => 'Javascript' ],
[ 'value' => 'C#' ]
];
echo json_encode( $data );
Here's a working example of my autocomplete code:
function get_data(type, target, min_length )
{
$(target).autocomplete({
source: function( request, response ) {
var submit = {
term: request.term,
type: type
};
$.ajax({
url: '/request/get',
data: { thisRequest: submit},
dataType: "json",
method: "post",
success: function( data ) {
response($.map( data.Data, function( item ) {
return {
label: item.label,
value: item.label
}
}));
}
});
},
minLength: min_length
})
}
<?php
$data = array(
'c++',
'Java',
'JavScript',"c#" );
echo json_encode($data);
?>
So i want with Pratik Soni advice and did a search. Here is the php code if anyone wants to use it
<?php
// Connect to server and select databse.
$dblink = mysql_connect('localhost','username','password') or die(mysql_error());
mysql_select_db('DB');
?>
<?php
if(!isset($_REQUEST['term']))
exit();
require('connect.php');
$term =
$query = mysql_query('
SELECT * FROM locations
WHERE name
LIKE "'.ucfirst($_REQUEST['term']).'%"
ORDER BY id ASC
LIMIT 0,10', $dblink
);
$data = array();
while($row = mysql_fetch_array($query, MYSQL_ASSOC)){
$data[] = array(
'label' => $row['name'],
'value' => $row['name'],
);
}
echo json_encode($data);
flush();
I need to make a form on my website that allows users to upload and send files. The form has 3 fields, Name, Email and Attachment.
I need all these 3 fields to be sent to me with the file attached to my email once the user clicks Send.
I have 3 files, the HTML file containing the form:
<div class="span6 control-group">
<label>File Upload:</label>
<input type="file" name="file_upload" id="file_upload" />
</div>
A .js file containing some visual effects for when the file is sent, if there is an error, required fields
var Contact = {
initialized: false,
initialize: function() {
if (this.initialized) return;
this.initialized = true;
this.build();
this.events();
},
build: function() {
this.validations();
},
events: function() {
},
validations: function() {
$("#contactForm").validate({
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "php/upload-form.php",
data: {
"name": $("#contactForm #name").val(),
"email": $("#contactForm #email").val(),
"quote": $("#contactForm #upload_file").val()
}, // Rest is visual effects, then ends with //
Contact.initialize();
And finally the upload-form.php
<?php
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));
header('Content-type: application/json');
require 'php-mailer/class.phpmailer.php';
$to = 'xxx#xxx.xxx';
$subject = $_POST['subject'];
if($to) {
$name = $_POST['name'];
$email = $_POST['email'];
$fields = array(
0 => array(
'text' => 'Name',
'val' => $_POST['name']
),
1 => array(
'text' => 'Email address',
'val' => $_POST['email']
),
2 => array(
'text' => 'File',
'val' => $_POST['file_upload']
)
);
$message = "";
foreach($fields as $field) {
$message .= $field['text'].": " . htmlspecialchars($field['val'], ENT_QUOTES) . "<br>\n";
}
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->From = $email;
$mail->FromName = $_POST['name'];
$mail->AddAttachment = $_POST['file_uploaded']; // attachment
$mail->AddAddress($to); // Add a recipient
$mail->AddReplyTo($email, $name);
);
$mail->IsHTML(true); // Set email format to HTML
$mail->CharSet = 'UTF-8';
$mail->Body = $name;
if(!$mail->Send()) {
$arrResult = array ('response'=>'error');
}
I searched everywhere, everything I got was people saying to add a
$mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
but it doesn't seem to work, the only answers I found on google were to attach files already on the server, but I want to attach files uploaded by users and then sent to my email, and if possible i want the files to be a temp file.
I'm a noob with PHP, so please help me. What am I doing wrong?
This should work to grab the file attachment and send it to your email
$mail->AddAttachment($_FILES['upload']['tmp_name']);
in $_FILES() the ['upload'] keyword represents the name of your file input. So adjust that accordingly.
If you want to send yourself an attachment with the actual attachment name, try this.
$mail->AddAttachment($_FILES['upload']['tmp_name'], $_FILES['upload']['name']);
What I've found to work pretty easy is set $_FILES['upload']['tmp_name'] and $_FILES['upload']['name'] as a variables.
So,
$file = $_FILES['upload']['tmp_name']
$file_name = $_FILES['upload']['name']
$mail->AddAttachment($file, $file_name );