【发布时间】:2016-01-05 22:43:07
【问题描述】:
我正在向 laravel 发出 Ajax 请求 - 但由于某种原因,我的自定义函数没有转义特殊字符。我不知道为什么。我在 CodeIgniter 中使用了这个完全相同的函数,它可以很好地转义输出。所有数据都很好地返回到 JS 文件 - 但它没有转义任何东西。代码如下:
public function store( Request $request, $project_id ) {
//current logged in user.
$user_id = auth()->user()->id;
//get all post inputs
$inputs = $request->all();
//make sure project ID belongs to current user. Stop someone from adding a task to your project that isn't you.
$projectBelongsToUser = Project::find(1)->where('user_id', $user_id)->where('id', $project_id)->get();
//if a project ID and inputs are provided - log them to the database, if not redirect to home with $errors.
if( $project_id && $inputs['description'] && $projectBelongsToUser ) {
$task = New Task;
$task->description = $inputs['description'];
$task->due_date = $inputs['due_date'];
$task->priority = $inputs['priority'];
$task->completed = 0;
$task->order = 0;
$task->user_id = $user_id;
$task->project_id = $project_id;
$task->save();
//get all tasks
$tasks = Task::where('user_id', $user_id)->where('project_id', $project_id)->orderBy('description', 'asc')->get();
//sanitize tasks for safe output
function sanitize_object_h( $array ) {
$array_modified = $array;
foreach( $array_modified as $object ) {
foreach( $object as &$item ) {
$item = htmlentities( $item, ENT_QUOTES );
}
//end foreach
}
//end foreach
return $array_modified;
}
//end sanitize_object_h
$sanitized_tasks = sanitize_object_h( $tasks );
//return the sanitized object.
echo json_encode( sanitize_object_h( $tasks ) );
} else {
echo "failed";
return;
}//end if
}//end store
【问题讨论】:
-
不知道你的问题,但是你有几个奇怪的东西,比如第一个 Project::find(1)... 你通过
id=1选择,但是使用user_id=$user_id,还有id=$project_id。这没有任何意义,id 只能是一个(在典型结构中),所以只有Project::find($project_id);。如果您想阻止人们使用其他人,请尝试角色和权限 -
@BojanKogoj 你会通过中间件(角色/权限)来做到这一点吗?一个是 user_id,另一个是 project_id。在项目表中存在与用户表的关系。
-
是的,我为此使用 Entrust。当然,要按照我的意愿进行一些工作,但如果你问我,这是值得的。保持代码简洁明了。
-
也不需要json_encode。它会自动为您完成,或使用 return Response::json($item)。始终返回值,不要回显它。
标签: laravel escaping output sanitize