2009-04-09

[PHP] 解析 URL 字串 parse_url , parse_str

parse_url 會解析一個標準的 URL 字串


<?php
$urlStr="http://user:passwd@host:80/path?a1=v1&a2=v2#anchor";
$url=parse_url($urlStr);
print_r($url);
/* output:
Array
(
[scheme] => http
[host] => host
[port] => 80
[user] => user
[pass] => passwd
[path] => /path
[query] => a1=v1&a2=v2
[fragment] => anchor
)
*/

echo parse_url($url, PHP_URL_SCHEME);
// prints: http

echo parse_url($url, PHP_URL_HOST);
// prints: host

echo parse_url($url, PHP_URL_PORT);
// prints: 80

echo parse_url($url, PHP_URL_USER);
// prints: user

echo parse_url($url, PHP_URL_PASS);
// prints: passwd

echo parse_url($url, PHP_URL_PATH);
// prints: /path

echo parse_url($url, PHP_URL_QUERY);
// prints: a1=v1&a2=v2

echo parse_url($url, PHP_URL_FRAGMENT);
// prints: anchor

?>



parse_str 會解析 URL Query 格式的字串
這裡特別注意,別使用下面的第一種方式直接解析 URL 上的 query
這會造成資安上的漏洞,這會讓外部可以直接修改裡面的變數值

<?php
$url_query = "city=new+york&id=3456&paid%5Bcurrency%5D=euro&paid%5Bamount%5D=345&paid%5Breceipt%5D=fgf"
parse_str($url_query);

echo $city;
// prints: new york

echo $id;
// prints: 3456

print_r($paid);
/* output:
Array
(
[currency] => euro
[amount] => 345
[receipt] => fgf
)
*/

/* 不建議上面的作法,因為會複寫原本的變數
* 造成資安上的漏洞
* */

parse_str($url_query, $query);
print_r($query);
/* output :
Array
(
[city] => new york
[id] => 3456
[paid] => Array
(
[currency] => euro
[amount] => 345
[receipt] => fgf
)

)*/
?>


參考來源:
Easy way to build GET query strings in php

0 回應: