Validate favicon on controller from form - php

i want to validate my file, only .ico files.
Laravel dont include x-icon mime I think, how can i validate it?
$logo = $request->file('logo');
$favicon = $request->file('favicon');
$request->validate([
'logo'=>'image|mimes:png',
'favicon'=>'',
]);

Make a custom validation rule as explained here.
In short:
First do:
php artisan make:rule CheckIfFavicon
Then:
Create the validation code in the created Rules-file.
Try something like:
public function passes($attribute, $value)
{
return $value->getClientOriginalExtension() == 'ico';
}
Then ad it to the validation. Note, that if you make a custom validation class you will have to change the syntax in the $request->validate([...]) from pipe-ing to array.
$request->validate([
'favicon' => [new CheckIfFavicon],
]);

use $file->getClientOriginalExtension() in code if you only want to check file extension
$ext = $file->getClientOriginalExtension();
if($ext == 'ico'){
//uploadfile
}else{
//do something else
}
use this as reference.

Related

How to verify a file is a "real file" in laravel validation

How to verify that an image is really an "Image" or a PDF is really a "PDF document" during the upload?
I observed a hack attempt to upload some files with jpg extension which has a picture preview but when I tried to open this file in an editor I saw php codes!
My concern is about:
How can I verify that a file is a real file?
Im using laravel framework, I tested with image mimes validation as shown below:
$inputs = array('image'=>$request->file('file'));
$rules = array(
'image' => 'mimes:jpeg,jpg,png,gif|required|max:10000'
);
$validator = Validator::make($inputs, $rules);
if ($validator->fails()){
die('validation failed');
}else{
die('validation Passed');
}
But this validation always pass if I try to upload the invalid jpeg file with some php injected codes!
Update:
invalid jpeg file attached
If you want to verify that it is an image, add the 'image' rule to your $rules array:
$rules = array(
'image' => 'image|mimes:jpeg,jpg,png,gif|required|max:10000'
);
https://laravel.com/docs/master/validation#rule-image
At last, i decided to check the file manually using the method -
file_get_contents(). I don't know whether this is an optimal solution. awaiting suggestions & recommendations :
public function validateFileContents($file,$needlesArray=null){
if(empty($needlesArray)){
$needlesArray = ['<?php','eval','base','gzuncomp'];
}
foreach($needlesArray as $needle){
if( strpos(file_get_contents($file),$needle) !== false) {
return false;
break;
}
}
return true;
}

Laravel php controller for pdf

I am wondering what to write in my laravel controller to allow me work with a pdf document posted from the front end by an AJAX request. I have found code online to check if an image is uploaded, but anyone have an idea what I need to do if it's a pdf document.
Please see my code below.
public function postUpload() {
$file = Input::file('image');
do something here.....
}
An example from documentation:
public function postUpload(Request $request) {
if ($request->hasFile('file')) {
$file = $request->file('file');
do something here.....
}
}
To check if file is PDF, use validation rules, like:
$rules = [
"file" => "mimes:pdf"
]

How to bind $_FILES to a Phalcon Form?

I have this part of code:
if ($this->request->isPost() && $this->request->hasFiles()) {
$post = $this->request->getPost();
$file = $this->request->getUploadedFiles();
if ($form->isValid($post)) {
$form->bind((array) $this->request->getPost(), $entity);
$entity->save();
// Do some other stuff
}
}
Is there a way to pass $file to a Phalcon\Forms\Form object?
Or another practice to check if validity of a form that contains both files and text?
To validate Files you must use the FileValidator Class as this example:
$file = new FileValidator([
'maxSize' => '10M',
'messageSize' => _('Your file is huge. Max allowed is 10 Mb'),
'allowedTypes' => ["image/jpeg", "image/png"],
'messageType' => _('File type is not permitted. Try with JPG, GIF, etc..'),
'messageEmpty' => _('Cannot be empty. Please upload a file')
]);
$this->validator->add('filesInputName', $file);
$messages = $this->validator->validate($_FILES);
This is a really old question, but as it affects my current project I share my solution.
Normally, I'm using form classes and validation classes, too. For validating a file upload along with other POST data, I simply combine both payloads:
$entity = new MyCustomModel();
$merged = array_merge($_POST, $_FILES);
if ($form->isValid($merged, $entity)) {
// ...
}

validating and save an uploaded ajax image in Yii

I need to send an image to server via an ajax request and it gets through just fine
and in my controller I can just use $_FILES["image"] to do stuff to it.
But I need to validate the image before I save it.
And in the Yii this can be achieved by doing something like this
$file = CUploadedFile::getInstance($model,'image');
if($model->validated(array('image'))){
$model->image->saveAs(Yii::getPathOfAlias('webroot') . '/upload/user_thumb/' . $model->username.'.'.$model->photo->extensionName);
}
But the problem is I don't have a $model, all I have is $_FILES["image"], now what should I put instead of the $model???
is there any other way where I can validate and save files without creating a model and just by Using $_FILES["image"]?
thanks for this awesome community... :)
Exists many ways how you can do upload. I want offer to you one of them.
1.You need to create model for your images.
class Image extends CActiveRecord {
//method where need to specify validation rules
public function rules()
{
return [
['filename', 'length', 'max' => 40],
//other rules
];
}
//this function allow to upload file
public function doUpload($insName)
{
$file = CUploadedFile::getInstanceByName($insName);
if ($file) {
$file->saveAs(Yii::getPathOfAlias('webroot').'/upload/user_thumb/'.$this->filename.$file->getExtensionName());
} else {
$this->addError('Please, select at least one file'); // for example
}
}
}
2.Now, need to create controller, where you will do all actions.
class ImageController extends CController {
public function actionUpload()
{
$model = new Image();
if (Yii::app()->request->getPost('upload')) {
$model->filename = 'set filename';
$insName = 'image'; //if you try to upload from $_FILES['image']
if ($model->validate() && $model->doUpload($insName)) {
//upload is successful
} else {
//do something with errors
$errors = $model->getErrors();
}
}
}
}
Creating a model might be overkill in some instances.
The $_FILE supervariable is part of the HTTP mechanism.
You can handle the copy by using the native PHP function move_uploaded_file()
$fileName = "/uploads/".myimage.jpg";
unlink($fileName);
move_uploaded_file($_FILES['Filedata']['tmp_name'], $fileName);
However, you lose the niceties of using a library that provides additional functionality and checks (eg file type and file size limitations).

Upload an image using Zend Framework?

I want to upload an image in Zend-framework.
In Application_Form_Test.php I write following code....
uploadImage = new Zend_Form_Element_File('uploadImage');
$uploadImage->setLabel("Upload Image ")
->setRequired(true)
->addValidator('Extension', false, 'jpeg,png')
->getValidator('Extension')->setMessage('This file type is not supportted.');
In the testAction() I write following code.....
$upload = new Zend_File_Transfer_Adapter_Http();
$upload->addValidator('Size', false, 52428800, 'image');
$upload->setDestination('uploads');
$files = $upload->getFileInfo();
foreach ($files as $file => $info) {
if ($upload->isValid($file)) {
$upload->receive($file);
}
}
Code is running successfully But I am not getting that image to the destination folder?
What may be the problem....?
Please help me.....
Thanks in advance....
I don't think that the getFileInfo() method is supposed to actually execute the file upload. I believe that in your controller action, you have to either call the getValues() method on the form object, or call the receiveFile() method on the form element.
See http://framework.zend.com/manual/en/zend.form.standardElements.html#zend.form.standardElements.file for the documentation examples.
An additional note: if you look in Zend_Form_Element_File->receive(), you will see that isValid() is called, so there's no need to clutter your controller with it. Here's what I do:
if ($upload->receive()) {
if ($upload->getFileName() && !file_exists($upload->getFileName())) {
throw new Exception('The upload should have worked, but somehow did not!');
}
} else {
throw new Exception(implode(PHP_EOL, $upload->getErrors()) . implode(PHP_EOL, $upload->getErrorMessages()));
}

Categories