首页 > 解决方案 > Laravel Blade 组件 - UTF-8 编码问题

问题描述

我目前正在使用 Laravel 8 版本开发应用程序。我已经构建了一个名为的组件input-group,它会导致我不理解的编码问题。该组件的代码如下所示:

<div class="form-group" {{ isset($attributes['style']) ? $attributes->merge(['style' => $attributes['style']]) : null }}>
    @if(isset($attributes['label']))
        <label for="{{ $attributes['id'] }}">{{ $attributes['label'] }}</label>
        <input type="text" 
               value="{{ isset($attributes['value']) ? $attributes['value'] : null }}" 
               class="form-control form-control-sm" 
               name="{{ $attributes['name'] }}" 
               id="{{ $attributes['id'] }}" 
               placeholder="{{ isset($attributes['placeholder']) ? $attributes['placeholder'] : null }}">
    @else 
        <input style="width:100%;" type="text" value="{{ isset($attributes['value']) ? $attributes['value'] : null }}" class="form-control form-control-sm" name="{{ $attributes['name'] }}" id="{{ $attributes['id'] }}" placeholder="{{ isset($attributes['placeholder']) ? $attributes['placeholder'] : null }}">
    @endif
  </div>

这是我注入value属性的数据=>Inspecteur de l'Education Nationale

这是我得到的输出<input>Inspecteur de l&#039;Education Nationale

我准确地说我的数据库(使用 mySQL)具有 Laravel 默认编码utf8mb4_unicode_ci。我用来获取这些数据的请求是一个经典的 Eloquent 请求(我不操纵编码)

mysql驱动的配置如下:

        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

标签: phplaravelencoding

解决方案


{!! !!}会工作,但我不会在这里使用它。

特别是如果您正在呈现的值有可能由用户设置,因为它未转义。这是一个潜在的漏洞,你让自己容易受到 XSS 攻击。

您可以改为:

{{ html_entity_decode($value) }},您仍然可以获得刀片帮助防止 XSS 攻击的好处。

您可以在此处阅读有关该功能的更多信息:https ://www.php.net/manual/en/function.html-entity-decode.php 。


推荐阅读