array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'ja', ), 'this' => array ( 0 => 'function.urlencode.php', 1 => 'urlencode', ), 'up' => array ( 0 => 'ref.url.php', 1 => 'URL 関数', ), 'prev' => array ( 0 => 'function.urldecode.php', 1 => 'urldecode', ), 'next' => array ( 0 => 'book.v8js.php', 1 => 'V8js', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'ja', 'path' => 'reference/url/functions/urlencode.xml', ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); ?>
(PHP 4, PHP 5, PHP 7, PHP 8)
urlencode — 文字列を URL エンコードする
string
エンコードする文字列。
-_.
を除くすべての非英数文字が % 記号
(%
)に続く二桁の16進数で置き換えられ、
空白は + 記号(+
)にエンコードされます。
同様の方法で、WWW のフォームからポストされたデータはエンコードされ、
application/x-www-form-urlencoded
メディア型も同様です。歴史的な理由により、この関数は » RFC 3986 エンコード(
rawurlencode() を参照ください) とは異なり、
空白を + 記号にエンコードします。
例1 urlencode() の例
<?php
$userinput = 'Data123!@-_ +';
echo "UserInput: $userinput\n";
echo '<a href="mycgi?foo=', urlencode($userinput), '">';
?>
上の例の出力は以下となります。
UserInput: Data123!@-_ + <a href="mycgi?foo=Data123%21%40-_+%2B">
例2 urlencode() および htmlentities() の例
<?php
$foo = 'Data123!@-_ +';
$bar = "Not the same content as $foo";
echo "foo: $foo\n";
echo "bar: $bar\n";
$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?>
上の例の出力は以下となります。
foo: Data123!@-_ + bar: Not the same content as Data123!@-_ + <a href="mycgi?foo=Data123%21%40-_+%2B&bar=Not+the+same+content+as+Data123%21%40-_+%2B">
注意:
HTML エンティティにマッチする変数については注意が必要です。 &、©、£ のようなものがブラウザから送信された 場合、エンティティの実体がその変数名の代わりに使用されます。 これは明らかな問題点であり、W3C が何年も指摘し続けてきたことです。 リファレンスは、» http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2 にあります。
PHP では、 .ini ディレクティブの arg_separator により引数のセパレータを W3C が推奨するセミコロンに変更することが可能です。残念なことに、多くの ユーザーエージントはこのセミコロン区切り形式でデータを送信しません。 よりポータブルな方法としては、セパレータに & の代わりに & を使用するというものがあります。この場合、PHP の arg_separator を変更する必要はありません。セパレータを & のままにし、htmlentities() あるいは htmlspecialchars() で URL をエンコードしてください。