Search code examples
phpsecuritylaravel-5sanitization

How to save data in database safe in laravel 5.1?


I won't have a Comment Form that anybody can fill it, and the input data will be inserted in the database after a validation:

<?php

namespace App\Http\Controllers;

use App\comments;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class CommentController  extends Controller
{
    public function postCommentNew( Request $request)
    {
        $this->validate($request, [
            'commenter' => 'required|max:255',
            'email' => 'required|max:255',
            'comment' => 'required',
            'post_id' => 'required'
        ]);
        comments::create( $request->all() );

        return redirect()->back()->with('success' , 'Comment Submited') ;
    }


}

now I want to be sure that nobody will not damage my site! I want to save data completely safe! I don't know if is it necessary to sanitize form input. if your answer is yes, How should I do it?

I have seen this here :

public function sanitize()
    {
        $input = $this->all();

        if (preg_match("#https?://#", $input['url']) === 0) {
            $input['url'] = 'http://'.$input['url'];
        }

        $input['name'] = filter_var($input['name'], FILTER_SANITIZE_STRING);
        $input['description'] = filter_var($input['description'], 
        FILTER_SANITIZE_STRING);

        $this->replace($input);     
    }

Solution

  • Regarding to Laravel 5.1 documentation:

    By default, Blade {{ }} statements are automatically sent through PHP's htmlentities function to prevent XSS attacks.

    So the answer is You do not need to build extra things to sanitize form input.

    Regarding SQL injection, Laravel uses PDO-prepared statements (Reference) and it is protected against possible SQL injection.

    The example in your question is intended to protect injection from URLs, which is fine.

    And finally, I have mentioned this link to you previously.

    It is not enough to count on documentation and my answer. Therefore, I would like to highlight this from the above link again:

    You need to do your penetration test when your project is done to Ensure everything is working and secured as planned