PHP の魔法の引用符

John Wachira 2023年6月20日
PHP の魔法の引用符

この記事では、PHP の addslashes() 関数について説明します。 定義済みの文字の前にバックスラッシュが付いた文字列を返します。

定義済みの文字は次のとおりです。

  1. 一重引用符 '
  2. 二重引用符 ''
  3. バックスラッシュ \
  4. ヌル

PHP の魔法の引用符

データベースやクエリに格納する文字列を準備するときに、この関数を実際に使用できます。

PHP のマジック クォートが廃止される前は、magic_quotes_gpc がデフォルトでオンになっていました。 デフォルトでは、$_GET/$_POST/$_COOKIES/$_REQUESTaddslashes() 関数を実行していました。

すでにエスケープされた文字列を常にチェックします。 このような文字列に対して addslashes() 関数を実行すると、ダブル エスケープが発生します。

get_magic_quotes_gpc() を使用して、文字列がエスケープされているかどうかを確認します。

構文:

addslashes(string)

以下のコードは、addslashes() 関数がどのように機能するかを示しています。

<?php
// PHP code to show the
// working of the addslashes() function

// String
$str = addslashes('delftstack provides "coding" lessons');

// prints the escaped string
echo($str);
?>

出力:

delftstack provides \"coding\" lessons

例 2:

<?php
$str = "My name's Chris.";
echo $str . " This is not secure in a database query.<br>";
echo addslashes($str) . " This is secure in a database query.";
?>

出力:

My name's Chris. This is not secure in a database query.
My name\'s Chris. This is secure in a database query.

addslashes() 関数は addcslashes() 関数とは異なることに注意することが重要です。

著者: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn