1
votes

In Laravel 5.4, when a form submission is made, the file(if any) in the request is passed to the Illuminate\Http\File or Illuminate\Http\UploadedFile instance. But let's say instead of the file, a url of that file is passed as the input. Naturally, the server will have to make a request to that input url to download the file. How will you validate the file in this scenario? (lets say I want to check if its an image or a video)

1

1 Answers

0
votes

As example you can use custom Validator class.

So basically we have controller which perform validation of form.

<?php

namespace App\Http\Controllers;

use App\Article;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Validator;

class ArticleController extends Controller
{
    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store($id = 0)
    {
        $rules = [
            'title'    => 'required',
            'body'     => 'required',
            'fileLink' => 'file_link',
        ];

        $validator = Validator::make(Input::all(), $rules);

        // process the login
        if ($validator->fails()) {

            return redirect()
                ->route('article.create')
                ->withErrors($validator);

        } else {

          //Other code
        }
    }

}

Then you have to create custom validator:

<?php

namespace App\Validators;

class FileLinkValidator
{
    public function validate($attribute, $value, $parameters, $validator)
    {
        $isValid = false;

        $ch = curl_init($value);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_exec($ch);

        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if($code == 200){
            $allowedContentTypes = [
                'image/jpeg'
            ];

            $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

            if(in_array($contentType,$allowedContentTypes)){
                $isValid = true;
            }
        }

        curl_close($ch);

        return $isValid;
    }
}

Register validator:

<?php

namespace App\Providers;

use Config;
use Illuminate\Support\ServiceProvider;
use Validator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('file_link', 'App\Validators\FileLinkValidator@validate','File Link should be valid url and contain file');
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
       //
    }
}

Then you can download file in controller and save it on disk and all metadata to database. But you have to perform another level of validation, to be more secure for users.