0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

laravelでレスポンスデータをエスケープする方法

Last updated at Posted at 2025-02-02

エスケープとは

プログラム内で特殊な意味を持つ文字を、普通の文字として扱うための技法です。

エスケープはセキュリティ上の観点からも非常に重要で、不正なデータがシステムに渡ることを防ぎ、クロスサイトスクリプティング(XSS)やSQLインジェクションなどの攻撃を防ぎます。

例えば、Webページにユーザーからの入力をそのまま表示する場合、下記のような悪意のあるスクリプトを表示してしまう可能性があります。このような場合、HTMLエスケープが必要です。

悪意のあるスクリプト
<script>alert('Hacked!');</script>
エスケープの例
"&lt;script&gt;alert(document.cookie);&lt;/script&gt;"

今回はLaravelで、レスポンスデータをエスケープするコードの一例を紹介します。

前提条件

PHP 8.3
Laravel 11.4

実際のコード

ミドルウェアでのエスケープ処理
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        // レスポンスがJSONの場合
        if ($response->headers->get('Content-Type') === 'application/json') {
            $content        = $response->getContent();
            $decodedContent = json_decode($content, true);
            
            // JSONデータをエスケープ
            if (is_array($decodedContent)) {
                array_walk_recursive($decodedContent, function (&$value) {
                    if (is_string($value)) {
                        $value = e($value);
                    }
                });

                $response->setContent(json_encode($decodedContent));
            }
        }
        // レスポンスが文字列の場合
        else if (is_string($response->getContent())) {
            $escapedContent = e($response->getContent());
            $response->setContent($escapedContent);
        }

        return $response;
    }

最後に

もっと良いコードがあったらコメントで教えて

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?