How to parse URL using PHP?
Components of a URL
- Scheme Name / Protocol
- Domain Name
- Port
- Path
- Query String
- Fragment Identifier
url_scheme://domain_name:port/path?query_string#fragment_id
Example URLhttp://www.mydomain.com:8080/update-user-details.php?user_id=23#general_settings
When your are developing web applications you may need to divide a URL in to components/parts. Sometimes you may need to get the host name from a URL or you may need to get the query string and divide it in to keys and values. This can easily do using php parse_url function. parse_url function returns an associative array of URL components. Keep in mind you have to provide a valid URL to parse. otherwise you may get incorrect results. Second parameter of parse_url function is optional. It is use to specify the URL component which you need to split.
1. Example code to parse URL using php.
<?php
/*
©-Copyright by kottawadumi.blogspot.com
*/
$url='https://www.yourdomain.com:443/edit-profile.php?user_id=23#personal_settings';
$url_components =parse_url($url);
foreach($url_components as $component=>$value){
echo $component.' -> '.$value.'<br/>';
}
?>
This example shows you how to divide the URL into parts. You can see the list of URL components and its values as the output.
2. How to get the host name of the URL using php?
<?php
/*
©-Copyright by kottawadumi.blogspot.com
*/
//Method one
$url='http://www.example.com:80/test.php?d=23#main';
$url_components =parse_url($url);
echo 'Domain name is '.$url_components['host'].'<br/>';
//Method two
$url_host=parse_url($url,PHP_URL_HOST);
echo 'Domain name is '.$url_host;
?>
This example shows you how to get the host name of a URL. You can directly pass the PHP_URL_HOST as the second parameter to the parse_url function. Then it will returns the domain name.
3. How to get the query string of a URL using php?
<?php
/*
©-Copyright by kottawadumi.blogspot.com
*/
//Method one
$url='http://www.photos.com/edit-photo?image_id=24&width=300&height=250&location=top';
$url_components =parse_url($url);
$query_string=$url_components['query'];
echo "Query String = ".$query_string.'<br/>';
//Method Two
echo 'Query String = '.parse_url($url,PHP_URL_QUERY);
//view query string parameters and values
$query = explode('&',$query_string);
foreach($query as $value){
echo $value.'<br/>';
}
?>
This example shows you how to get query string parameters using php. Basically query string comes after the question mark. You can use & sign to split parameters. If you want to divide parameters and values you can further split the result using equal sign.
0 comments:
Post a Comment