|
|
 |
parse_url (PHP 3, PHP 4, PHP 5) parse_url -- Parse a URL and return its components Descriptionarray parse_url ( string url )
This function returns an associative array containing any of the
various components of the URL that are present. If one of them is
missing, no entry will be created for it. The components are :
This function is not meant to validate
the given URL, it only breaks it up into the above listed parts. Partial
URLs are also accepted, parse_url() tries its best to
parse them correctly.
Note:
This function doesn't work with relative URLs.
Example 1. parse_url() example $ php -r 'print_r(parse_url("http://username:password@hostname/path?arg=value#anchor"));'
Array
(
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)
$ php -r 'print_r(parse_url("http://invalid_host..name/"));'
Array
(
[scheme] => http
[host] => invalid_host..name
[path] => /
) |
|
See also pathinfo(), parse_str(),
dirname(), and basename().
User Contributed Notes
parse_url
levi at alliancesoftware dot com dot au
15-Mar-2005 08:02
The documentation doesn't explicitly mention it, but if parse_url fails it will return false
grey - greywyvern - com
09-Mar-2005 06:15
NOTE:
It's not mentioned in the documentation, but parse_url will trigger a WARNING level error on the following string: "http://" but not "http:/" or "http://w"
Make sure to account for this if "http://" is a possible string you might send to this function.
scott a t connerly d o t net
06-Mar-2005 01:34
re: <b>osfist at yahoo dot com</b>'s http_implode function.
Here is a companion function for that:
function http_explode($stringInput) {
if (! is_string($stringInput))
return false;
$arr_query=NULL;
$args=explode('&',$stringInput);
foreach($args as $arg) {
$parts=explode('=',$arg);
$arr_query[$parts[0]]=$parts[1];
} return $arr_query;
}
TheShadow
30-Dec-2004 02:36
corey at eyewantmedia dot com
22-Dec-2004 11:18
Just in case this helps someone, this is a quick and dirty way to add or replace values to your query string, which I found especially useful when modifying urls to allow paging through resultsets.
/**
* @return string
* @param string $varName
* @param string $varVal
* @param string $uri
* @desc Returns the a string that is either
* $uri if you pass it or the current
* uri with the variable name $varName
* equal to the value urlencode($varVal)
* It replaces a current value if it find
* it or adds the variable and value pair
* if they are new.
*/
function AddToQuery($varName, $varVal, $uri=null) {
$result = '';
$beginning = '';
$ending = '';
if (is_null($uri)) {//Piece together uri string
$beginning = $_SERVER['PHP_SELF'];
$ending = ( isset($_SERVER['QUERY_STRING']) ) ? $_SERVER['QUERY_STRING'] : '';
} else {
$qstart = strpos($uri, '?');
if ($qstart === false) {
$beginning = $uri; //$ending is '' anyway
} else {
$beginning = substr($uri, 0, $qstart);
$ending = substr($uri, $qstart);
}
}
if (strlen($ending) > 0) {
$vals = array();
$ending = str_replace('?','', $ending);
parse_str($ending, $vals);
$vals[$varName] = $varVal;
$ending = '';
$count = 0;
foreach($vals as $k => $v) {
if ($count > 0) { $ending .= '&'; }
else { $count++; }
$ending .= "$k=" . urlencode($v);
}
} else {
$ending = $varName . '=' . urlencode($varVal);
}
$result = $beginning . '?' . $ending;
return $result;
}
duellj at gmail dot com
12-Oct-2004 05:13
A quick note about something that tripped me up:
the url you are parsing must include the scheme, or it will be parsed into the 'path' key.
Example:
<?
$parsed = parse_url("www.php.net");
print_r($parsed);
?>
esm at baseclass dot modulweb dot dk
17-Aug-2004 08:32
Hi
I did an URL Validator that also parses the URL into subparts. The validator does not use PHP specific functions, so it can be easily ported to javascript or another language. If you are looking at this page, chances are my validator might interest you.
http://baseclass.modulweb.dk/urlvalidator
Regards
Aceb
matt at cryptography dot com
09-May-2004 03:36
Modified version of glue_url()
Cox's,Anonimous fucntion
<?php
function glue_url($parsed) {
if (! is_array($parsed)) return false;
$uri = $parsed['scheme'] ? $parsed['scheme'].':'.((strtolower($parsed['scheme']) == 'mailto') ? '':'//'): '';
$uri .= $parsed['user'] ? $parsed['user'].($parsed['pass']? ':'.$parsed['pass']:'').'@':'';
$uri .= $parsed['host'] ? $parsed['host'] : '';
$uri .= $parsed['port'] ? ':'.$parsed['port'] : '';
$uri .= $parsed['path'] ? $parsed['path'] : '';
$uri .= $parsed['query'] ? '?'.$parsed['query'] : '';
$uri .= $parsed['fragment'] ? '#'.$parsed['fragment'] : '';
return $uri;
}
?>
osfist at yahoo dot com
01-Mar-2004 01:11
Functions to edit a url query key and its value.
You can also add a new query key and its value.
I gathered and modified useful functions for my code.
It works fine as you see at the test result.
<?php
function get_query_edited_url($url, $arg, $val) {
$parsed_url = parse_url($url);
parse_str($parsed_url['query'],$url_query);
$url_query[$arg] = $val;
$parsed_url['query'] = http_implode($url_query);
$url = glue_url($parsed_url);
return $url;
}
function http_implode($arrayInput) {
if (! is_array($arrayInput))
return false;
$url_query="";
foreach ($arrayInput as $key=>$value) {
$url_query .=(strlen($url_query)>1)?'&':"";
$url_query .= urlencode($key).'='.urlencode($value);
}
return $url_query;
}
function glue_url($parsed) {
if (! is_array($parsed))
return false;
$url = $parsed['scheme'] ? $parsed['scheme'].':'
.((strtolower($parsed['scheme']) == 'mailto') ? '':'//'): '';
$url .= $parsed['user'] ? $parsed['user']
.($parsed['pass']? ':'.$parsed['pass']:'').'@':'';
$url .= $parsed['host'] ? $parsed['host'] : '';
$url .= $parsed['port'] ? ':'.$parsed['port'] : '';
$url .= $parsed['path'] ? $parsed['path'] : '';
$url .= $parsed['query'] ? '?'.$parsed['query'] : '';
$url .= $parsed['fragment'] ? '#'.$parsed['fragment'] : '';
return $url;
}
?>
alan at zeroasterisk dot com
22-Dec-2003 03:06
<?
function linkprep($link)
{
$link_array=parse_url($link);
$return= str_replace($link_array['query'], rawurlencode($link_array['query']), $link);
$return= str_replace($link_array['fragment'], rawurlencode($link_array['fragment']), $return);
return $return;
}
?>
sjt at 5jt dot com
21-Oct-2003 09:45
It gets better...
parse_str($_SERVER['QUERY_STRING']);
though you might flinch at random names from the URI query string showing up as variables. Safer to secure them in a hash table, eg
parse_str($_SERVER['QUERY_STRING'],$vars);
$lang = $vars['lang'];
echo "Your language is $lang";
sjt
"inerte" is my hotmail.com username
10-Oct-2003 12:35
Regarding claude_minette at hotmail dot com note about variables from a previous page, here's an easier way:
$tab = parse_url($_SERVER['HTTP_REFERER']);
parse_str($tab['query']);
claude_minette at hotmail dot com
30-Jul-2003 07:00
if you need, (for a reason or another), to get back the query as variables in your new page, use this... ;-)
$origin=$_SERVER["HTTP_REFERER"];
$tab=parse_url($origin);
$query=$tab["query"];
$variables=explode("&",$query);
for ($i=0;$i<=count($variables);$i++){
$tab=explode("=",$variables[$i]);
$$tab[0]=$tab[1];
}
It seems to be working... ;-)
Min's
Daniel Malament
07-Feb-2003 11:38
My version of the glue function, and adding/removing parts of query strings...
function unparse_url($parts_arr) {
if (strcmp($parts_arr['scheme'], '') != 0) {
$ret_url = $parts_arr['scheme'] . '://';
}
$ret_url .= $parts_arr['user'];
if (strcmp($parts_arr['pass'], '') != 0) {
$ret_url .= ':' . $parts_arr['pass'];
}
if ((strcmp($parts_arr['user'], '') != 0) || (strcmp($parts_arr['pass'], '') != 0)) {
$ret_url .= '@';
}
$ret_url .= $parts_arr['host'];
if (strcmp($parts_arr['port'], '') != 0) {
$ret_url .= ':' . $parts_arr['port'];
}
$ret_url .= $parts_arr['path'];
if (strcmp($parts_arr['query'], '') != 0) {
$ret_url .= '?' . $parts_arr['query'];
}
if (strcmp($parts_arr['fragment'], '') != 0) {
$ret_url .= '#' . $parts_arr['fragment'];
}
return $ret_url;
}
function add_query_arg($url, $arg, $val) {
$parts_arr = parse_url($url);
if (strcmp($parts_arr['query'], '') != 0) $parts_arr['query'] .= '&';
$parts_arr['query'] .= $arg . '=' . $val;
return unparse_url($parts_arr);
}
function remove_query_arg($url, $arg) {
$parts_arr = parse_url($url);
if (!strcmp($parts_arr['query'], '')) return $url;
$query_arr = explode('&', $parts_arr['query']);
foreach ($query_arr as $k => $v) {
if ((preg_match('/^'.$arg.'=/', $v)) || (preg_match('/^'.$arg.'$/', $v))) {
unset($query_arr[$k]);
}
}
$parts_arr['query'] = implode('&', $query_arr);
return unparse_url($parts_arr);
}
bermi.ferrer ) a t ( akelos d·o·t com
01-Feb-2003 05:23
This is a small update for Steve's function. It removes the Argument even if its repeated more than once in the URL.
This function performance is better than the one I posted before (delete_value_from_url).
function RemoveArgFromURL($URL,$Arg)
{
while($Pos = strpos($URL,"$Arg="))
{
if ($Pos)
{
if ($URL[$Pos-1] == "&")
{
$Pos--;
}
$nMax = strlen($URL);
$nEndPos = strpos($URL,"&",$Pos+1);
if ($nEndPos === false)
{
$URL = substr($URL,0,$Pos);
}
else
{
$URL = str_replace(substr($URL,$Pos,$nEndPos-$Pos),'',$URL);
}
}
}
return $URL;
}
steve at mg-rover dot org
24-Jan-2003 11:59
An alternative and more straightforward to the remove an argument from a URL code above is below. I'm not saying its any better than the one above, but its easier to read ;) :p
----------------
function RemoveArgFromURL($URL,$Arg)
{
$Pos = strpos($URL,"$Arg=");
if ($Pos)
{
if ($URL[$Pos-1] == "&")
{
// If Pos-1 is pointing to a '&' knock Pos back 1 so its removed.
$Pos--;
}
$nMax = strlen($URL);
$nEndPos = strpos($URL,"&",$Pos+1);
if ($nEndPos === false)
{
// $Arg is on the end of the URL
$URL = substr($URL,0,$Pos);
}
else
{
// $Arg is in the URL
$URL = str_replace(substr($URL,$Pos,$nEndPos-$Pos),'',$URL);
}
}
return $URL;
}
----------------
flop at escapesoft dot net
06-Dec-2002 11:22
Modified version of glue_url()
Cox's,Anonimous fucntion
function glue_url($parsed) {
if (! is_array($parsed)) return false;
$uri = $parsed['scheme'] ? $parsed['scheme'].':'.((strtolower($parsed['scheme']) == 'mailto') ? '':'//'): '';
$uri .= $parsed['user'] ? $parsed['user'].($parsed['pass']? ':'.$parsed['pass']:'').'@':'';
$uri .= $parsed['host'] ? $parsed['host'] : '';
$uri .= $parsed['port'] ? ':'.$parsed['port'] : '';
$uri .= $parsed['path'] ? $parsed['path'] : '';
$uri .= $parsed['query'] ? '?'.$parsed['query'] : '';
$uri .= $parsed['fragment'] ? '#'.$parsed['fragment'] : '';
return $uri;
}
knoj at knoj dot com
16-Jun-2002 07:28
If you would ever need to rebuild a URL when all you have is the path (saved in a db in my case), or to provide an index link back to the main http://www.whatever.com but you don't always know if your URL will be the same, then you can use this:
$url = parse_url($PHP_SELF);
$host = str_replace($url[path],"",$PHP_SELF);
print($host);
That will remove anything after the .com, .net, .org, or what ever the TDL is.
Anonimous
09-May-2002 07:51
Modified version of glue_url() Cox's fucntion.
----------------------------------------------
// $parsed is a parse_url() resulting array
function glue_url($parsed) {
if (! is_array($parsed)) return false;
if (isset($parsed['scheme'])) {
$sep = (strtolower($parsed['scheme']) == 'mailto' ? ':' : '://');
$uri = $parsed['scheme'] . $sep;
} else {
$uri = '';
}
if (isset($parsed['pass'])) {
$uri .= "$parsed[user]:$parsed[pass]@";
} elseif (isset($parsed['user'])) {
$uri .= "$parsed[user]@";
}
if (isset($parsed['host'])) $uri .= $parsed['host'];
if (isset($parsed['port'])) $uri .= ":$parsed[port]";
if (isset($parsed['path'])) $uri .= $parsed['path'];
if (isset($parsed['query'])) $uri .= "?$parsed[query]";
if (isset($parsed['fragment'])) $uri .= "#$parsed[fragment]";
return $uri;
}
Tomas V dot V dot Cox <cox at idecnet dot com>
19-Feb-2001 05:16
Perhaps someday you need to modify somefield from the parse_url() and then build the url again with this data.
To make it, here I post the "glue_url" function:
// param $url is the result array from the parse_url()
function glue_url ($url){
if (!is_array($url)){
return false;
}
// scheme
$uri = (!empty($url['scheme'])) ? $url['scheme'].'://' : '';
// user & pass
if (!empty($url['user'])){
$uri .= $url['user'].':'.$url['pass'].'@';
}
// host
$uri .= $url['host'];
// port
$port = (!empty($url['port'])) ? ':'.$url['port'] : '';
$uri .= $port;
// path
$uri .= $url['path'];
// fragment or query
if (isset($url['fragment'])){
$uri .= '#'.$url['fragment'];
} elseif (isset($url['query'])){
$uri .= '?'.$url['query'];
}
return $uri;
}
| |