URL (Uniform Resource Locator) often termed as web address is a unique reference of web resource that is accessible on the internet.To visit any website user go to the browser (chrome, firefox, safari) and type any website name like wdb24.com and browser loads requested website.But URLs are not restricted with http/https. URLs are also used in ftp (file transfer protocol), email (mailto), database access and many other applications.A typical URL look something like this.
If you want read more about URL then visit https://en.wikipedia.org/wiki/URL
In PHP, there are bundle of functions which handle URL and its fragments quite well. So in this post, I am going to show you 10 PHP built in functions and their use.
PHP Built in URL Functions:
1) parse_url():
This function parses the url and return its components. It is a very handy function and use frequently in php projects.
Syntax: parse_url(string $url, optional $component)
$url | URL to parse |
$component | Specify any Component otherwise blank will return an array. Components are PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY or PHP_URL_FRAGMENT |
parse_url example 1:
1 2 3 4 |
$parseUrl = parse_url("http://www.example.com"); print_r($parseUrl); |
The output of the above code is below. Parse url split url into 2 indices. First one is scheme which is http and second is a host name which is www.example.com
Output:
1 2 3 4 5 6 7 |
Array ( [scheme] =>http [host] => www.example.com ) |
parse_url example 2:
1 2 3 4 |
$parseUrl2 = parse_url("http://www.example.com:8080?name=ahsan&title=developer#hrefID"); print_r($parseUrl2); |
In the above code, a very long url passed in parse_url function and parse_url split url into different indexes of array.
Output:
1 2 3 4 5 6 7 8 9 10 |
Array ( [scheme] =>http [host] => www.example.com [port] => 8080 [query] =>name=ahsan&title=developer [fragment] =>hrefID ) |
parse_url example 3:
1 2 3 4 |
$ftpURL = parse_url('ftp://user:password@example.com/pub/file.txt'); print_r($ftpURL); |
In the above example ftp url with user, password and file path pass in the parse_url and parse_url split ftp url into different indexes.
Output:
1 2 3 4 5 6 7 8 9 10 |
Array ( [scheme] =>ftp [host] => example.com [user] =>user [pass] =>password [path] => /pub/file.txt ) |
2) get_headers():
This function fetch array (indexed or associative) of all the headers send by the server in response to a HTTP request.
Syntax: get_headers( string $url [, int $format = 0 ] )
$url | Target url |
$format | is an optional parameter. If non-zero value pass in $format then it returns array with string keys |
get_header example 1:
1 2 3 4 5 |
$url = 'https://en.wikipedia.org/wiki/Main_Page'; $getHeader = get_headers($url); echo $getHeader; |
In the above snippet I created $url
and pass Wikipedia main page link. $getHeader
variable calls get_header function with $url
. You may notice that I haven’t pass second argument in get_header function. In the output it returns indexed array.
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
Array ( [0] => HTTP/1.1 200 OK [1] => Date: Wed, 10 Jan 2018 17:16:28 GMT [2] => Content-Type: text/html; charset=UTF-8 [3] => Content-Length: 73776 [4] => Connection: close [5] => Server: mw1264.eqiad.wmnet [6] => X-Powered-By: HHVM/3.18.6-dev [7] => P3P: CP="This is not a P3P policy! See https://en.wikipedia.org/wiki/Special:CentralAutoLogin/P3P for more info." [8] => X-Content-Type-Options: nosniff [9] => Content-language: en [10] => X-UA-Compatible: IE=Edge [11] => Vary: Accept-Encoding,Cookie,Authorization [12] => Link: ;rel=preload;as=image;media=not all and (min-resolution: 1.5dppx),;rel=preload;as=image;media=(min-resolution: 1.5dppx) and (max-resolution: 1.999999dppx),;rel=preload;as=image;media=(min-resolution: 2dppx) [13] => Last-Modified: Wed, 10 Jan 2018 17:13:11 GMT [14] => Backend-Timing: D=86332 t=1515604404810786 [15] => X-Varnish: 1058144681 1046743861, 666702041 635785624, 978505582 972640080 [16] =>Via: 1.1 varnish-v4, 1.1 varnish-v4, 1.1 varnish-v4 [17] => Age: 183 [18] => X-Cache: cp1054 hit/6, cp3043 hit/6, cp3041 hit/4282 [19] => X-Cache-Status: hit-front [20] => Strict-Transport-Security: max-age=106384710; includeSubDomains; preload [21] => Set-Cookie: WMF-Last-Access=10-Jan-2018;Path=/;HttpOnly;secure;Expires=Sun, 11 Feb 2018 12:00:00 GMT [22] => Set-Cookie: WMF-Last-Access-Global=10-Jan-2018;Path=/;Domain=.wikipedia.org;HttpOnly;secure;Expires=Sun, 11 Feb 2018 12:00:00 GMT [23] => Cache-Control: private, s-maxage=0, max-age=0, must-revalidate [24] => Accept-Ranges: bytes ) |
get_header example 2:
1 2 3 4 5 |
$url = 'https://en.wikipedia.org/wiki/Main_Page'; $getHeader = get_headers($url,1); echo $getHeader; |
Above is same as example 1 except I passed 1 as a second parameter in get_headers. Now it returns same array as example 1 but in array will be associative.
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
Array ( [0] => HTTP/1.1 200 OK [Date] => Wed, 10 Jan 2018 17:16:29 GMT [Content-Type] => text/html; charset=UTF-8 [Content-Length] => 73776 [Connection] =>close [Server] => mw1264.eqiad.wmnet [X-Powered-By] => HHVM/3.18.6-dev [P3P] => CP="This is not a P3P policy! See https://en.wikipedia.org/wiki/Special:CentralAutoLogin/P3P for more info." [X-Content-Type-Options] =>nosniff [Content-language] =>en [X-UA-Compatible] => IE=Edge [Vary] => Accept-Encoding,Cookie,Authorization [Link] => ;rel=preload;as=image;media=not all and (min-resolution: 1.5dppx),;rel=preload;as=image;media=(min-resolution: 1.5dppx) and (max-resolution: 1.999999dppx),;rel=preload;as=image;media=(min-resolution: 2dppx) [Last-Modified] => Wed, 10 Jan 2018 17:13:11 GMT [Backend-Timing] => D=86332 t=1515604404810786 [X-Varnish] => 1058144681 1046743861, 666702041 635785624, 985019039 972640080 [Via] => 1.1 varnish-v4, 1.1 varnish-v4, 1.1 varnish-v4 [Age] => 184 [X-Cache] =>cp1054 hit/6, cp3043 hit/6, cp3041 hit/4311 [X-Cache-Status] => hit-front [Strict-Transport-Security] => max-age=106384710; includeSubDomains; preload [Set-Cookie] => Array ( [0] => WMF-Last-Access=10-Jan-2018;Path=/;HttpOnly;secure;Expires=Sun, 11 Feb 2018 12:00:00 GMT [1] => WMF-Last-Access-Global=10-Jan-2018;Path=/;Domain=.wikipedia.org;HttpOnly;secure;Expires=Sun, 11 Feb 2018 12:00:00 GMT ) [X-Analytics] =>ns=0;page_id=15580374;https=1;nocookies=1 [Cache-Control] =>private, s-maxage=0, max-age=0, must-revalidate [Accept-Ranges] =>bytes ) |
3) get_meta_tags():
This function extracts all meta tag content attributes from a file and returns an array.
Syntax: parse_url(string $filename, bool $use_include_path = false)
$filename | The path to the HTML file, as a string. This can be a local file or an URL |
$use_include_path | Set use_include_path to TRUE will result in PHP trying to open the file along the standard include path as per the include_path directive. This is used for local files, not URLs |
get_meta_tags example 1:
1 2 3 4 |
$tags = get_meta_tags('https://www.wdb24.com'); print_r($tags); |
In the above code, I passed wdb24.com url into get_meta_tags function and it will print all meta tags of wdb24.com page in a associative array.
Output:
1 2 3 4 5 6 7 8 9 10 |
Array ( [viewport] =>width=device-width, initial-scale=1.0 [description] => WDB24.com is a Web Development Blog which provides tutorials and code snippets. Specially focus on PHP, MySql, HTML, CSS, Javascript, jQuery. [robots] =>noodp [generator] => WordPress 4.8.4 [msapplication-tileimage] => https://www.wdb24.com/wp-content/uploads/2017/10/cropped-favicon-270x270.png ) |
4) http_build_query():
This function creates a URL-encoded query string from the associative (or indexed) array provided. This function is mostly used in cURL.
Syntax: http_build_query($query_data [, string $numeric_prefix [, string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] )
$query_data | single or multi-dimensional array.It can be object too, if it is an object only public properties will be incorporated. |
$numeric_prefix | If numeric indices are used in the base array and this parameter is provided, it will be prepended to the numeric index for elements in the base array only. |
$arg_separator | is used to separate arguments but may be overridden by specifying this parameter. |
$enc_type | By default, PHP_QUERY_RFC1738 |
http_build_query example 1:
1 2 3 4 |
$array1 = array("ahsan","wdb24","web developer"); echo http_build_query($array1); |
I passed indexed array to http_build_query function and it will return url-encoded string as below.
Output:
1 2 3 |
0=ahsan&1=wdb24&2=web+developer |
http_build_query example 2:
1 2 3 4 |
$array2 = array("ahsan","wdb24","web developer"); echo http_build_query($array2,"var_"); |
Above code is almost same like example 1 but in http_build_query I passed second parameter as “var_”. Now this function use var_ as a prefix of url-encoded keys.
Output:
1 2 3 |
var_0=ahsan&var_1=wdb24&var_2=web+developer |
http_build_query example 3:
1 2 3 4 |
$array3 = array("name"=>"ahsan","job_title"=> "web developer", "email" =>"ahsan@example.com"); echo http_build_query($array3); |
$array3
is an associative array and when I passed $array3
to http_build_query. It will generate below url-encoded string.
Output:
1 2 3 |
name=ahsan&job_title=web+developer&email=ahsan%40example.com |
http_build_query example 4:
1 2 3 4 |
$array4 = array("29","male","name"=>"ahsan","job_title"=> "web developer", "email" =>"ahsan@example.com"); echo http_build_query($array4,"my_var_"); |
In the above example $array4
is an array with mixed values. First 2 indices of $array4
has no keys and rest of three have keys. Then in the next line I passed “my_var” as a second parameter in http_build_query. “my_var” will only apply to first 2 indices of $array4 because they don’t have any key define.
Output:
1 2 3 |
my_var_0=29&my_var_1=male&name=ahsan&job_title=web+developer&email=ahsan%40example.com |
5) urlencode():
This function encode string. This function is mostly use in url, as a convenient way to pass variable to next page.
Syntax: urlencode( string $str )
$str | The string to be encoded |
urlencode example 1:
1 2 3 4 |
$urlEncode = "http://www.example.com?address = ".urlencode('House no. ABC, London'); echo $urlEncode; |
Output:
1 2 3 |
http://www.example.com?address = House+no.+ABC%2C+London |
6) urldecode():
This function decodes url encoding string.Decodes any %## encoding in the given string. Plus symbols (‘+’) are decoded to a space character.
Syntax: urldecode( string $str )
$str | The string to be decoded |
urldecode example 1:
1 2 3 4 5 |
$urlEncode = "http://www.example.com?address = ".urlencode('House no. ABC, London'); $urlDecode = urldecode($urlEncode); echo $urlDecode; |
Output:
1 2 3 |
http://www.example.com?address = House no. ABC, London |
7) rawurlencode():
This function encode url according to RFC 3986.
Syntax: rawurlencode( string $str )
$str | Url to be encoded |
rawurlencode example 1:
1 2 3 4 |
$rawUrlHref1 = "http://www.example.com?address = ".rawurlencode('House no. ABC, London'); echo $rawUrlHref1; |
Output:
1 2 3 |
http://www.example.com?address = House%20no.%20ABC%2C%20London |
rawurlencode example 2:
1 2 3 4 5 |
$rawUrlHref2 = "http://www.example.com?email=".rawurlencode('ahsan@abc.com')."&token=".rawurlencode('b$v2c$6x!>c'); echo $rawUrlHref2; |
Output:
1 2 3 |
http://www.example.com?email=ahsan%40abc.com&token=b%24v2c%246x%21%3Ec |
8) rawurldecode():
This function decode url encoded string
Syntax: rawurldecode( string $str )
$str | Url to be decoded |
rawurldecode example 1:
1 2 3 4 5 |
$rawUrlHref1 = "http://www.example.com?address = ".rawurlencode('House no. ABC, London'); $decodeRawUrl = rawurldecode($rawUrlHref1); echo$decodeRawUrl; |
Output:
1 2 3 |
http://www.example.com?address = House no. ABC, London |
rawurldecode example 2:
1 2 3 4 5 |
$rawUrlHref2 = "http://www.example.com?email=".rawurlencode('ahsan@abc.com')."&token=".rawurlencode('b$v2c$6x!>c'); $decodeRawHref2 = rawurldecode($rawUrlHref2); echo$decodeRawHref2; |
Output:
1 2 3 |
http://www.example.com?email=ahsan@abc.com&token=b$v2c$6x!>c |
9) base64_encode():
This function encode data with MIME base64. This function take 33% more space than original data.
Syntax: base64_encode( string $data )
$data | Data to encode |
base64_encode example 1:
1 2 3 4 5 |
$text = "This will be base64 encoded text"; $base64Encode = base64_encode ($text); echo $base64Encode; |
Output:
1 2 3 |
VGhpcyB3aWxsIGJlIGJhc2U2NCBlbmNvZGVkIHRleHQ= |
10) base64_decode():
This function decodes data with MIME base64
Syntax: base64_decode( string $data [, bool $strict = false ] )
$data | Encoded data |
$strict | Default value set for $strict is false. If this value change to true, then it will return false if character in encoded data are not base64 alphabet. Otherwise invalid characters will be silently discarded. |
base64_decode example 1:
1 2 3 4 5 6 |
$text = "This text will convert into base64 then it will decode"; $base64Encode = base64_encode ($text); $base64Decode = base64_decode($base64Encode); echo $base64Decode; |
Output:
This text will convert into base64 then it will decode.
Also read:
- PHP get random User Agent Function
- How to install GIT on Windows 10
- How to install XAMPP on Windows 10
- PHP read text file and insert into MySQL database
- How to fetch single row from Database in PHP