我在Laravel中有这样的简化代码:
$uid = $request->input('uid');
DB::table('users')->insert([
'uid' => DB::raw("CONV('$uid', 16, 10)"),
'created_at' => date("Y-m-d H:i:s")
]);
我的代码容易受到SQL注入攻击吗?又为什么呢?如果是这样,我该如何预防呢?
是的,它容易受到SQL注入的攻击,因为$uid
的原始内容将注入到您的sql查询中。
尽管DB::raw()
接受准备好的参数,但不能在insert方法内部正确使用。
为此,您需要手动编写插入查询:
$uid = $request->input('uid');
DB::statement('INSERT INTO users (uid, created_at) VALUES (CONV(?, 16, 10), ?)', [
$uid,
date("Y-m-d H:i:s")
]);
使用create
方法
更改用户模型
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password' , 'uid'
];
}
并且在您的控制器中
$uid = $request->input('uid');
User::create([
'uid' => DB::raw("CONV('$uid', 16, 10)"),
'created_at' => date("Y-m-d H:i:s")
]);