★ wanayoo — archive 1999 http://uk.php.net/manual/cs/function.parse-url.phpNouvelle recherche | Portail wanayoo
PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<http_build_queryrawurldecode>
view the version of this page
Last updated: Thu, 08 Jan 2004

parse_url

(PHP 3, PHP 4 )

parse_url -- Rozebrat URL a vrátit její komponenty

Popis

array parse_url ( string url)

Tato funkce vrátí asociativní pole všech komponent URL přítomnych v url. Ty mohou být: "scheme", "host", "port", "user", "pass", "path", "query" a "fragment".



add a note add a note User Contributed Notes
parse_url
alan at zeroasterisk dot com
22-Dec-2003 06:06
<?
/*
Alan -- here is a useful function for displaying links...  if you don't do this, an improper query string could mess up html code...  (by having a > or " or something...)

If you have simple improvements or flaws, please email me. [at]zeroasterisk[d0t]com
*/

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
22-Oct-2003 12: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 03: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 10: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 02: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 08: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 02: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 02: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;
}
xmontero at dsitelecom dot com
20-Sep-2002 10:03
Hi.

If you ever need to call a php script itself with modified parameters in the query, it may be useful this piece of code.

Just imagine you write a "viewer" with 1000 results and you want to show "page=1" then provide links to "page=2", "page=3" and so on. If you request the URL and simply append the page at the end, you might result in duplicated values in the URI, like "table=customers&page=1&page=2".

I use the modifies version of cox gluer, posted by anonimous an dmodified it a little bit:

// The next function takes a query like "page=2" or "page=2&name=xavi" and uses it to override the self parameters

   function everything_self_uri( $new_query )
   {
       global $REQUEST_URI;                            // Get the current URI used for the script
       $parsed=parse_url( $REQUEST_URI );                // Split into parts

       if( isset($parsed['scheme']) )                                            // Begin to rebuild it
       {
           $sep = (strtolower($parsed['scheme']) == 'mailto' ? ':' : '://');
           $uri = $parsed['scheme'] . $sep;
       }
       else
       {
           $uri = '';
       }

       if( isset($parsed['pass']) )                                            // Continue to rebuild it.
       {
           $uri .= "$parsed[user]:$parsed[pass]@";
       }
       elseif( isset($parsed['user']) )
       {
           $uri .= "$parsed[user]@";
       }

       if ( isset( $parsed['host']    ) ) { $uri .= $parsed['host'];      }    // Continue to rebuild it.
       if ( isset( $parsed['port']    ) ) { $uri .= ":$parsed[port]";    }    // Continue to rebuild it.
       if ( isset( $parsed['path']    ) ) { $uri .= $parsed['path'];      }    // Continue to rebuild it.
       if ( isset( $parsed['query']    ) ) { $uri .= "?" . everything_mix_query( $parsed[query], $new_query );    }    // Continue to rebuild it.
       if ( isset( $parsed['fragment'] ) ) { $uri .= "#$parsed[fragment]"; }    // End to rebuild it.

       return $uri;
   }

// The next function is the mixer itself

   function everything_mix_query( $old_query, $new_query )
   {
       // This function takes two queries and returns one single query.
       // The queries are for URLs. An example of query is: "name=michael&destination=London"
       // This function puts all the params of every query and if one param is repeated in the first and the second, the "new_query" remains, while
       // the "old_query" looses its value.

       $old_query_array = explode( "&", $old_query );
       $new_query_array = explode( "&", $new_query );

       $result_query_array = array();                            // Empty a new array

       $old_count = count( $old_query_array );                    // Count the old parameters
       for( $i = 0; $i < $old_count; $i++ )                    // Add the old parameters
       {
           $current_item = $old_query_array[ $i ];                    // Ex: Current item = "name=xavi"
           $pair = explode( "=", $current_item );                    // Ex: Pair = {"name", "xavi"}
           $key = $pair[ 0 ];                                        // Ex: Key = "name"
           $result_query_array[ $key ] = $old_query_array[ $i ];    // Ex: $result[ "name" ] = "name=xavi"
       }

       $new_count = count( $new_query_array );                    // Count the new parameters
       for( $i = 0; $i < $new_count; $i++ )                    // Add the new parameters
       {
           $current_item = $new_query_array[ $i ];                    // Ex: Current item = "name=smith"
           $pair = explode( "=", $current_item );                    // Ex: Pair = {"name", "smith"}
           $key = $pair[ 0 ];                                        // Ex: Key = "name"
           $result_query_array[ $key ] = $new_query_array[ $i ];    // Ex: $result[ "name" ] = "name=smith"
       }

       $result_query = implode( "&", $result_query_array );

       return $result_query;
   }

// You can now call the whole thing like this:

$URI = everything_self_uri( "page=3" );
echo( '<a href="' . $URI . '">Click here</a>' );

Hope to help. If you can copy/paste this code, I'm then happy ;-)

See you.
Xavier Montero.
knoj at knoj dot com
16-Jun-2002 10: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 10: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;
}
sjohnson at fuzzygroup dot com
16-Mar-2002 03:51
Just a note but this tripped me up in a quick cut and paste of the code. 

If you use this function on something that is a valid host name already then in the [url] element is nothing.
Tomas V dot V dot Cox <cox at idecnet dot com>
19-Feb-2001 08: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;
}

<http_build_queryrawurldecode>
 Last updated: Thu, 08 Jan 2004
show source | credits | sitemap | contact | mirror sites 
Copyright © 2001-2004 The PHP Group
All rights reserved.
This mirror generously provided by: Kewlio.net Limited
Last updated: Wed Jan 28 21:14:52 2004 GMT