Remove imgur from uploading images - php

A few months ago a friend of mine added in my cms created in laravel the upload of images via imgur, only that I would like to remove it, on the cms however the images are saved (locally) I would like to remove the upload on imgur and I would like to stay the images locally
public function imageProfile(Request $request)
{
$user = Auth::user();
$rules = array(
'profile-image' => 'required|image|mimes:jpeg,png,jpg,gif|max:8192|dimensions:min_width=160,min_height=160',
);
$customMessages = [
'profile-image.required' => 'E\' richiesta una immagine per cambiare immagine di profilo.',
'profile-image.image' => 'Devi inserire un immagine valida.',
'profile-image.mimes' => 'L\'immagine inserita non ha un formato adatto.',
'profile-image.dimensions' => 'L\'immagine deve essere minimo 160x160.',
];
$validator = Validator::make(Input::all(), $rules, $customMessages);
if ($validator->fails()) {
return response()->json(['success' => false, 'error' => $this->validationErrorsToString($validator->errors())]);
}
if ($request->hasFile('profile-image')) {
$number = mt_rand(1,1000000);
$image = $request->file('profile-image');
$name = $user->username.'-'.Carbon::now()->toDateString().'-'.$number.'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/profile');
$imagePath = $destinationPath. "/". $name;
$image->move($destinationPath, $name);
$image = Imgur::setHeaders([
'headers' => [
'authorization' => 'Client-ID MY CLIENT ID',
'content-type' => 'application/x-www-form-urlencoded',
]
])->setFormParams([
'form_params' => [
'image' => URL::to("/").'/uploads/profile/'. $name,
]
])->upload(URL::to("/").'/uploads/profile/'. $name);
\File::delete('uploads/profile/' .$name);
$user->image_profile = $image->link();
$user->save();
$html = $image->link();
return response()->json(['success' => true, 'html' => $html, 'image' => $image->link()]);
}
}
My server is running Ubuntu 16.04 + Laravel 5.5
Best Regards

This code will only upload photo to your local directory.
public function imageProfile(Request $request)
{
$user = Auth::user();
$rules = array(
'profile-image' => 'required|image|mimes:jpeg,png,jpg,gif|max:8192|dimensions:min_width=160,min_height=160',
);
$customMessages = [
'profile-image.required' => 'E\' richiesta una immagine per cambiare immagine di profilo.',
'profile-image.image' => 'Devi inserire un immagine valida.',
'profile-image.mimes' => 'L\'immagine inserita non ha un formato adatto.',
'profile-image.dimensions' => 'L\'immagine deve essere minimo 160x160.',
];
$validator = Validator::make(Input::all(), $rules, $customMessages);
if ($validator->fails()) {
return response()->json(['success' => false, 'error' => $this->validationErrorsToString($validator->errors())]);
}
if ($request->hasFile('profile-image')) {
$number = mt_rand(1,1000000);
$image = $request->file('profile-image');
$name = $user->username.'-'.Carbon::now()->toDateString().'-'.$number.'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/profile');
$imagePath = $destinationPath. "/". $name;
$image->move($destinationPath, $name);
// remove this commented portion
// $image = Imgur::setHeaders([
// 'headers' => [
// 'authorization' => 'Client-ID MY CLIENT ID',
// 'content-type' => 'application/x-www-form-urlencoded',
// ]
// ])->setFormParams([
// 'form_params' => [
// 'image' => URL::to("/").'/uploads/profile/'. $name,
// ]
// ])->upload(URL::to("/").'/uploads/profile/'. $name);
// \File::delete('uploads/profile/' .$name);
// $user->image_profile = $image->link();
// $user->save();
// $html = $image->link();
// update this portion to
$user->image_profile = $imagePath;
$user->save();
$html = $imagePath;
// return response()->json(['success' => true, 'html' => $html, 'image' => $image->link()]);
// also update this portion to
return response()->json(['success' => true, 'html' => $html, 'image' => $imagePath]);
}
}

Related

how to generate pdf from yii2fullcalendar?

Im trying to generate a pdf file from month and day views of philipfrenzel-yii2fullcalendar with kartik-mpdf and I get this error
Invalid data received for parameter "events".
To do it, I've generated an actionIndexPdf($events) method in the controller and a index_pdf.php view file with the yii2fullcalendar widget receiving $events as parameter.
The problem is in the renderPartial of the action. It seems it has a problem with the array of events.
The code is as follows:
Controller CalendarioController.php
public function actionIndex() {
$calendario = Calendario::find()->all();
$events = [];
foreach ($calendario as $cal) {
$event = new \yii2fullcalendar\models\Event();
$event->id = $cal->id;
$event->title = $cal->pedido->cliente->nombre;
$event->id_pedido = $cal->pedido->id;
$event->sector = $cal->pedido->cliente->sector;
$event->direccion = $cal->pedido->cliente->direccion;
$event->telefono = $cal->pedido->cliente->telefono;
$event->textColor = '#302B16';
switch ($cal->pedido->estado) {
case 0:
$event->estado = 'Pendiente de entrega';
break;
case 1:
$event->estado = 'Entregado sin deuda';
break;
case 2:
$event->estado = 'Entregado con deuda';
break;
}
$event->start = $cal->pedido->fecha_solicitud;
$event->end = $cal->pedido->fecha_entrega;
$event->color = $cal->pedido->color;
$event->allDay = false;
$events[] = $event;
}
return $this->render('index', [
'events' => $events
]);
}
public function actionIndexPdf($events) {
die(var_dump($events));
Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
$formatter = \Yii::$app->formatter;
$pdf = new Pdf([
'mode' => Pdf::MODE_CORE, // leaner size using standard fonts
'format' => Pdf::FORMAT_LETTER,
'orientation' => Pdf::ORIENT_PORTRAIT,
'destination' => Pdf::DEST_BROWSER,
//Se renderiza la vista "pdf" (que abrirá la nueva ventana)
'content' => $this->renderPartial('index_pdf', ['events' => $events]),
'options' => [
// any mpdf options you wish to set
],
'cssFile' => '#vendor/kartik-v/yii2-mpdf/src/assets/kv-mpdf-bootstrap.min.css',
'cssInline' => 'body{
font-size:12px;
}',
]);
return $pdf->render();
}
View index_pdf.php
<?php
/* #var $this yii\web\View */
/* #var $searchModel app\models\CalendarioSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Calendario de Pedidos';
$this->params['breadcrumbs'][] = $this->title;
?>
<p>
<?= yii2fullcalendar\yii2fullcalendar::widget([
'events' => $events,
'id' => 'calendar',
'options' => [
'lang' => 'es',
],
'clientOptions' => [
'selectable' => false,
'editable' => true,
'droppable' => true,
'header' => [
'left' => 'prev,next,today',
'center' => 'title',
'right' => 'month,listDay',
],
'height' => 'auto',
'displayEventTime' => false,
],
]);
?>
</p>
button in index.php view
<p>
<?php
//Imprime el boton generar pdf
// die(var_dump($events));
echo Html::a('Generar PDF', ['index-pdf', 'events' => $events],
[
'class' => 'btn btn-success',
'target'=>'_blank',
'data-toggle'=>'tooltip',
// 'title'=>'Will open the generated PDF file in a new window'
]);
?>
</p>
You are trying to pass an array of data as a GET parameter on this line:
echo Html::a('Generar PDF', ['index-pdf', 'events' => $events],
I imagine that passing the events array is not a requirement for you, in that case, it would be much easier to have both methods generate the array.
Since you are using the same code to get the events on both methods, index and index_pdf, you could extract that code and call it in both methods to get the $events.
You could move the code out of the controller, into a helper class for example, but, for simplicity, I will just add an example using a method inside the same controller.
private function getCalendarEvents() {
$events = [];
foreach (Calendario::find()->each() as $cal) {
$event = new \yii2fullcalendar\models\Event();
$event->id = $cal->id;
$event->title = $cal->pedido->cliente->nombre;
$event->id_pedido = $cal->pedido->id;
$event->sector = $cal->pedido->cliente->sector;
$event->direccion = $cal->pedido->cliente->direccion;
$event->telefono = $cal->pedido->cliente->telefono;
$event->textColor = '#302B16';
switch ($cal->pedido->estado) {
case 0:
$event->estado = 'Pendiente de entrega';
break;
case 1:
$event->estado = 'Entregado sin deuda';
break;
case 2:
$event->estado = 'Entregado con deuda';
break;
}
$event->start = $cal->pedido->fecha_solicitud;
$event->end = $cal->pedido->fecha_entrega;
$event->color = $cal->pedido->color;
$event->allDay = false;
$events[] = $event;
}
return $events;
}
Then call it on both actions
public function actionIndex() {
return $this->render('index', [
'events' => $this->getCalendarEvents()
]);
}
public function actionIndexPdf() {
$events = $this->getCalendarEvents();
Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
$formatter = \Yii::$app->formatter;
$pdf = new Pdf([
'mode' => Pdf::MODE_CORE, // leaner size using standard fonts
'format' => Pdf::FORMAT_LETTER,
'orientation' => Pdf::ORIENT_PORTRAIT,
'destination' => Pdf::DEST_BROWSER,
//Se renderiza la vista "pdf" (que abrirá la nueva ventana)
'content' => $this->renderPartial('index_pdf', ['events' => $events]),
'options' => [
// any mpdf options you wish to set
],
'cssFile' => '#vendor/kartik-v/yii2-mpdf/src/assets/kv-mpdf-bootstrap.min.css',
'cssInline' => 'body{
font-size:12px;
}',
]);
return $pdf->render();
}
If passing the event array as a parameter is a requirement, you will probably need to serialize it to generate the link, and then deserialize it on the index_pdf action.

Why is my validator is not validating in Laravel?

Why is my validator is not validating the input-email field, it accepts anything!
This is my controller to update the database. The name in form is correct
Edit: This is my entire code, I post here my code with just email but one guy said that is working, so why this is not working with my entire code of update database?
public function atualizar(Request $req)
{
$erros = [
'input-nome.max' => 'Introduziu carateres acima do máximo no campo do nome!',
'input-facebook.max' => 'Introduziu carateres acima do máximo no campo do facebook!',
'input-instagram.max' => 'Introduziu carateres acima do máximo no campo do instagram!',
'input-descricao.max' => 'Introduziu carateres acima do máximo no campo da descrição!',
'input-profissao.max' => 'Introduziu carateres acima do máximo no campo da profissão!',
'input-imagem.max' => 'O tamanho máximo do ficheiro é de 10mb!',
'image' => 'O ficheiro que inseriu não é imagem!',
'mimes' => 'A extensão da imagem não é permitida, apenas JPEG, JPG e PNG!',
'email' => 'Introduza um e-mail válido!'
];
$validator = Validator::make($req->all(), [
'input-nome' => 'max:25',
'input-email' => 'nullable|required_with:input-email|email:rfc,dns,filter',
'input-facebook' => 'max:40',
'input-instagram' => 'max:40',
'input-profissao' => 'max:25',
'input-descricao' => 'max:120',
'input-imagem' => 'image|mimes:jpeg,png,jpg|max:10240'
], $erros);
$id = $req->input('input-id');
$membrosEquipa = DB::table('equipa')
->where('id', $id)
->get();
$inputEmail = $req->input('input-email');
if (!isset($inputEmail)) {
$inputEmail = null;
}
if ($req->filled('input-email')) {
$inputEmail = $req->input('input-email');
}
$inputNome = $req->input('input-nome');
$inputFacebook = $req->input('input-facebook');
$inputInstagram = $req->input('input-instagram');
$inputProfissao = $req->input('input-profissao');
$inputDescricao = $req->input('input-descricao');
$inputImagem = $req->file('input-imagem');
foreach ($membrosEquipa as $membro) {
if (!isset($inputNome)) {
$inputNome = $membro->nome;
}
if (!isset($inputFacebook)) {
$inputFacebook = $membro->facebook;
}
if (!isset($inputInstagram)) {
$inputInstagram = $membro->instagram;
}
if (!isset($inputProfissao)) {
$inputProfissao = $membro->profissao;
}
if (!isset($inputDescricao)) {
$inputDescricao = $membro->descricao;
}
if (isset($inputImagem)) {
Storage::delete($membro->imagem);
$inputImagem = $req->file('input-imagem')->store('storage/equipa');
} else {
$inputImagem = $membro->imagem;
}
}
$timestamp = date('Y-m-d H:i:s');
DB::table('equipa')
->where('id', $id)
->update([
'nome' => $inputNome,
'email' => $inputEmail,
'facebook' => $inputFacebook,
'instagram' => $inputInstagram,
'profissao' => $inputProfissao,
'descricao' => $inputDescricao,
'imagem' => $inputImagem,
'updated_at' => $timestamp
]);
return redirect('/editar/equipa/')->with('status', 'Membro da equipa atualizado com sucesso');
}
you must use below code after define $validator
$validator = Validator::make($req->all(), [
'input-email' => 'email:rfc,dns|required'
], $erros);
if ($validator->fails())
{
return redirect()->back()->withErrors($validator)->withInput();
}

Laravel 5.4 Image validation is not working

I'm kinda stuck here on images validation in laravel. I have to validation the file input must be an image and for that I used the classical way of laravel validation but I don't why it is not working any clue?
User Controller
public function createProfile(Request $request) {
$phoneNumber=$request->phoneNumber;
if (empty($request->except(['userId','token']))){
$data= array(
'nickName' => '',
'profilePic' => '',
'phoneNumber' => '',
'userHeight' => '',
'userWeight' => '',
'userVertical' => '',
'userSchool' => '',
'homeTown' => '',
);
$this->setMeta("200", "Success");
$this->setData("userDetails", $data);
return response()->json($this->setResponse());
}
if($phoneNumber) {
$validationData= array(
'phoneNumber' => $phoneNumber,
);
$validationRules = array(
'phoneNumber' => [
'regex:/^[0-9]+$/',
'min:10',
'max:15',
Rule::unique('users')->ignore($request->userId, 'userId'),
]
);
if($request->has('profilePic')){
$validationData['profilePic'] = $request->profilePic;
$validationRules['profilePic'] = 'image|mimes:jpeg,bmp,png';
}
$validator = Validator::make($validationData,$validationRules);
if ($validator->fails()) {
$errors = $validator->errors();
if ($errors->first('phoneNumber')) {
$message = $errors->first('phoneNumber');
} else if ($errors->first('profilePic')) {
$message = $errors->first('profilePic');
} else {
$message = Constant::MSG_422;
}
$this->setMeta("422", $message);
return response()->json($this->setResponse());
}
}
$homeTown = $request->homeTown;
$filename='';
$profilePic=$request->file('profilePic');
if(!empty($profilePic)) {
$destinationPath = public_path() . '/uploads/users';
$filename = "image_" . Carbon::now()->timestamp . rand(111, 999) . ".jpg";
$profilePic->move($destinationPath, $filename);
}
$user = User::where('userId',$request->userId)->first();
if($request->hasFile('profilePic')){
$user->profilePic = $filename;
}
$user->nickName=$request->nickName;
$user->phoneNumber=$request->phoneNumber;
$user->userHeight=$request->userHeight;
$user->userWeight=$request->userWeight;
$user->userVertical=$request->userVertical;
$user->userSchool=$request->userSchool;
$user->homeTown=$homeTown;
$user->save();
$this->setMeta("200", "Profile Changes have been successfully saved");
$this->setData("userDetails", $user);
return response()->json($this->setResponse());
}
I would assume the reason your validation isn't working is because you adding the rule inside:
if($request->has('profilePic')){
This needs to be $request->hasFile('profilePic').
Hope this helps!
you can use as like this i think it is better.....
if($request->hasFile('profilePic')){
$rules = array(
'profilePic' => 'required | mimes:jpeg,jpg,png',
);
}
$validator = Validator::make($request->all(), $rules);
Just use this for validation. If you have to handle condition then go through step by step debuging.
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:5120',
'description' => 'required'
]);

Laravel uploading multiple images doesn't work, also mimes don't

I'm trying to upload images in Laravel using this code:
public function postAddPictures(Request $request)
{
// getting all of the post data
$files = $request->file('cover_image');
// Making counting of uploaded images
$file_count = count($files);
// start count how many uploaded
$uploadcount = 0;
foreach($files as $file) {
$messages = [
'cover_image.required' => 'U moet een afbeelding opgeven.',
'cover_image.image' => 'De bestanden moeten een afbeelding zijn (jpeg, png, bmp, gif, or svg).',
'description.required' => 'U moet een beschrijving opgeven.'
];
$rules = [
'cover_image' => 'required',//|mimes:png,gif,jpeg,jpg,bpm,svg
'album_id' => 'required|numeric|exists:albums,id',
'description' => 'required'
];
$validate = ['file'=> $file, 'description' => $request->get('description'), 'album_id'=> $request->get('album_id')];
$validator = Validator::make($validate, $rules, $messages);
if ($validator->fails()) {
return Redirect::to('admin/pictures/add')->withInput()->withErrors($validator);
}
$random_name = str_random(8);
$destinationPath = 'public/uploads/pictures/rallypodium/website/'.Album::find($request->get('album_id'))->type.'/'.Album::find($request->get('album_id'))->name.'/';
$extension = $file->getClientOriginalExtension();
$filename = $random_name.'_album_image.'.$extension;
$uploadSuccess = $file->move($destinationPath, $filename);
Images::create([
'description' => $request->get('description'),
'image' => $filename,
'album_id'=> $request->get('album_id')
]);
$uploadcount ++;
}
if($uploadcount == $file_count){
Activity::log('heeft foto's in de map map "'.ucwords(str_replace('-', ' ', Album::find($request->get('album_id'))->name)).'" toegevoegd.');
$request->session()->flash('alert-success', 'Foto's succesvol toegevoegd.');
return Redirect::to('admin/pictures/add');
}
}
The problem here is, it keeps returning the error message 'U moet een afbeelding opgeven.'. It doesn't store the data in the database nor uploads the files.
This are my fields in HTML:
cover_image
album_id
description
Could someone help me out? I tried different ways already but I can't find the solution at all.
Kindest regards,
Robin
Instead of a key 'file' you should use key 'cover_image' if you want to validate all files one by one.
$validate = ['cover_image'=> $file, 'description' => $request->get('description'), 'album_id'=> $request->get('album_id')];

Laravel 5.2 Validator for text and multiple files

I've been having some trouble validating multiple files and text at same time.
when I validate the whole request $request->all(); the file rules wont work.
'file' => 'required|mimes:png,jpeg,jpg,gif|max:3000'.
That gets fixed if I only validate the files in an array array('file'=> $file), but this way I cant validate the other inputs.
I got the multiple files part from the internet, and added my part for the other inputs, here's my function:
public function createNewPost(Request $request) {
$post = new Post;
$post->user_id = Auth::user()->id;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->status= "borrador";
$post->save();
$post->img = "/uploads/posts/".$post->id;
$post->save();
$files = Input::file('file');
$file_count = count($files);
$uploadcount = 0;
foreach($files as $file) {
$rules = array(
'file' => 'required|mimes:png,jpeg,jpg,gif|max:3000',
'title' => 'required|unique:posts|max:255',
'body' => 'required'
);
$messages = [
'title.required' => 'Sin titulo?',
'body.required' => 'No has escrito nada',
'file.required' => 'Selecciona al menos 1 imagen.',
'file.mimes' => 'No puedes utilizar ese tipo de imagen, intenta con (jpg/png/jpeg).',
'file.max' => 'El total de imagenes no puede pesar mas de 3MB.'
];
$validator = Validator::make(array('file'=> $file), $rules, $messages);
if($validator->passes()){
$destinationPath = 'uploads/posts/'.$post->id;
//$filename = $file->getClientOriginalName();
$filename = $uploadcount.".".$file->getClientOriginalExtension();
$upload_success = $file->move($destinationPath, $filename);
$uploadcount ++;
}
}
if($uploadcount == $file_count){
Session::flash('success', 'Upload successfully');
return Redirect::to('/admin/post/new');
}
else {
return Redirect::to('/admin/post/new')->withInput()->withErrors($validator);
}
}
Try this, and remove your foreach files loop:
$files = count($this->input('file')) - 1;
foreach(range(0, $files) as $index) {
$rules['file.' . $index] = 'required|mimes:png,jpeg,jpg,gif|max:3000';
}
Source

Categories