PHP 常用函数-url函数

urlencode 和 rawurlencode

urlencode 和 rawurlencode 两个函数都用来编码 URL 字符串。除了 -_. 之外的所有非字母数字字符都将被替换成百分号(%)后跟两位十六进制数。

差异:

  • 对于空格,urlencode 编码为加号(+)。此编码与 FORM 表单 POST 数据的编码方式是一样的,同时与 application/x-www-form-urlencoded 的媒体类型编码方式一样。
  • 对于空格,rawurlencode 根据 RFC3896 编码为 %20。

示例:

<?php

$s = 'asdf1234-!-@-#-$-%-^-&-*-(-)- -';

echo urlencode($s).'<br>'; // urlencode 将空格变为+
echo rawurlencode($s); // rawurlencode 将空格变为%20

输出:

asdf1234-%21-%40-%23-%24-%25-%5E-%26-%2A-%28-%29-+-
asdf1234-%21-%40-%23-%24-%25-%5E-%26-%2A-%28-%29-%20-

urldecode 和 rawurldecode

对于 urldecode,解码字符串中的任何 %##,加号 + 被解码成一个空格字符。

对于 rawurldecode,解码字符串中的任何 %##

base64_encode 和 base64_decode

将数据编码为 MIME base64 格式(通常用于转换二进制数据),或从 MIME base64 格式解码数据。Base64-encoded 数据要比原始数据多占用 33% 左右的空间。

http_build_query

用于将对象或者一维或多维的关联(或下标)数组生成一个经过 URL-encode 的请求字符串。定义如下“”

string http_build_query ( mixed $query_data [, string $numeric_prefix [, string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] )

可以指定 arg_separator 使用自定义分隔符,指定 enc_type 以确定如何编码加号 +。

<?php
$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

echo http_build_query($data) . "
";
echo http_build_query($data, '', '&amp;');

输出:

foo=bar&baz=boom&cow=milk&php=hypertext+processor
foo=bar&amp;baz=boom&amp;cow=milk&amp;php=hypertext+processor

parse_url

解析一个 URL 并返回一个关联数组,包含在 URL 中出现的各种组成部分。数组中可能的键有以下几种:

  • scheme - 协议,如 http
  • host - 主机名
  • port - 端口号
  • user
  • pass
  • path - 路径
  • query - GET 参数,在问号 ? 之后
  • fragment - 在散列符号 # 之后
<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));

echo parse_url($url, PHP_URL_PATH);

输出:

Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)
/path

get_headers

取得服务器响应 HTTP 请求所发送的所有标头。

<?php
$url = 'http://www.example.com';

print_r(get_headers($url));

print_r(get_headers($url, 1));

输出:

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Date: Sat, 29 May 2004 12:28:13 GMT
    [2] => Server: Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
    [4] => ETag: "3f80f-1b6-3e1cb03b"
    [5] => Accept-Ranges: bytes
    [6] => Content-Length: 438
    [7] => Connection: close
    [8] => Content-Type: text/html
)

Array
(
    [0] => HTTP/1.1 200 OK
    [Date] => Sat, 29 May 2004 12:28:14 GMT
    [Server] => Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
    [ETag] => "3f80f-1b6-3e1cb03b"
    [Accept-Ranges] => bytes
    [Content-Length] => 438
    [Connection] => close
    [Content-Type] => text/html
)
原文地址:https://www.cnblogs.com/kika/p/10851533.html