suche nach in der

rawurldecode> <http_build_query
Last updated: Fri, 18 May 2012

view this page in

parse_url

(PHP 4, PHP 5)

parse_urlAnalysiert einen URL und gibt seine Bestandteile zurück

Beschreibung

mixed parse_url ( string $url [, int $component = -1 ] )

Diese Funktion parst einen URL und gibt ein assoziatives Array zurück, das die im URL vorhandenen Komponenten enthält.

Diese Funktion ist nicht dazu gedacht, einen gegebenen URL zu validieren, sondern es gliedert einen URL in die unten aufgeführten Bestandteile. Unvollständige URLs werden als Parameter akzeptiert, parse_url() versucht, sie bestmöglich zu analysieren.

Parameter-Liste

url

Der zu parsende URL. Ungültige Zeichen werden durch _ ersetzt.

component

Geben Sie einen der folgenden Parameter an, um nur einen spezifischen Teil des URL als String zu erhalten: PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY oder PHP_URL_FRAGMENT.

Rückgabewerte

Bei sehr fehlerhaften URLs kann parse_url() FALSE zurückgeben und wirft E_WARNING. Andernfalls wird ein assoziatives Array zurückgegeben, dessen Bestandteile sich wie folgt zusammensetzen können (mindestens ein Bestandteil liegt vor):

  • scheme - z.B. http
  • host
  • port
  • user
  • pass
  • path
  • query - alles nach dem Fragezeichen ?
  • fragment - alles nach dem Textanker #

Ist der Parameter component angegeben, wird ein String anstelle des normalen Array zurückgegeben.

Changelog

Version Beschreibung
5.1.2 component-Parameter hinzugefügt
5.3.3 E_WARNING für fehlerhafte URLs entfernt.

Beispiele

Beispiel #1 Ein parse_url()-Beispiel

<?php
$url 
'http://benutzername:passwort@hostname/pfad?argument=wert#textanker';

print_r(parse_url($url));

echo 
parse_url($urlPHP_URL_PATH);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Array
(
    [scheme] => http
    [host] => hostname
    [user] => benutzername
    [pass] => passwort
    [path] => /pfad
    [query] => argument=wert
    [fragment] => textanker
)
/pfad

Anmerkungen

Hinweis:

Diese Funktion verarbeitet keine relativen URLs.

Hinweis:

Die Funktion ist primär dazu gedacht, URLs zu parsen, nicht jedoch URIs. Um jedoch die Abwärtskompatibilität von PHP zu gewährleisten, wird für das Schema file:// die Ausnahme dreier Slashes (file:///) zugelassen. Bei allen anderen Schemata ist diese Notierung ungültig.

Siehe auch



add a note add a note User Contributed Notes
parse_url
Elliott Brueggeman
04-Jun-2007 12:59
Note that if you pass this function a url without a scheme (www.php.net, as opposed to http://www.php.net), the function will incorrectly parse the results. In my test case it returned the domain under the ['path'] element and nothing in the ['host'] element.
Marc-Antoine Ross
14-Mar-2007 05:10
Do not look for the fragment in $_SERVER['QUERY_STRING'], you will not find it. You should read the fragment in JavaScript for example.
alistair at 21degrees dot com dot au
24-Oct-2006 04:21
Heres a simple function to add the $component option in for PHP4. Haven't done exhaustive testing, but should work ok.

<?php

   
## Defines only available in PHP 5, created for PHP4
   
if(!defined('PHP_URL_SCHEME')) define('PHP_URL_SCHEME', 1);
    if(!
defined('PHP_URL_HOST')) define('PHP_URL_HOST', 2);
    if(!
defined('PHP_URL_PORT')) define('PHP_URL_PORT', 3);
    if(!
defined('PHP_URL_USER')) define('PHP_URL_USER', 4);
    if(!
defined('PHP_URL_PASS')) define('PHP_URL_PASS', 5);
    if(!
defined('PHP_URL_PATH')) define('PHP_URL_PATH', 6);
    if(!
defined('PHP_URL_QUERY')) define('PHP_URL_QUERY', 7);                       
    if(!
defined('PHP_URL_FRAGMENT')) define('PHP_URL_FRAGMENT', 8);   
   
    function
parse_url_compat($url, $component=NULL){
       
        if(!
$component) return parse_url($url);
       
       
## PHP 5
       
if(phpversion() >= 5)
            return
parse_url($url, $component);

       
## PHP 4
       
$bits = parse_url($url);
       
        switch(
$component){
            case
PHP_URL_SCHEME: return $bits['scheme'];
            case
PHP_URL_HOST: return $bits['host'];
            case
PHP_URL_PORT: return $bits['port'];
            case
PHP_URL_USER: return $bits['user'];
            case
PHP_URL_PASS: return $bits['pass'];
            case
PHP_URL_PATH: return $bits['path'];
            case
PHP_URL_QUERY: return $bits['query'];
            case
PHP_URL_FRAGMENT: return $bits['fragment'];
        }
       
    }

?>
dawalama at gmail dot com
04-Oct-2006 06:48
With few modifications

    /**
     * source: http://us2.php.net/manual/en/function.parse-url.php#60237
     * Edit the Query portion of an url
     *
     * @param    string    $action    ethier a "+" or a "-" depending on what action you want to perform
     * @param    mixed    $var    array (+) or string (-)
     * @param    string    $uri    the URL to use. if this is left out, it uses $_SERVER['PHP_SELF']
     * @version      1.0.0
     */
    function change_query($action, $var = NULL, $uri = NULL) {

               if (($action == "+" && !is_array($var)) || ($action == "-" && $var == "") || $var == NULL) {
                       return FALSE;
               }

               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
                               $ending = "";
                       } else {
                               $beginning = substr($uri, 0, $qstart);
                               $ending = substr($uri, $qstart);
                       }
               }

               $vals = array ();
               $ending = str_replace('?', '', $ending);
               parse_str($ending, $vals);

               switch ($action) {
                       case '+' :
                               $vals[$var[0]] = $var[1];
                               break;
                       case '-' :
                               if (isset ($vals[$var])) {
                                       unset ($vals[$var]);
                               }
                               break;
                       default :
                               break;
               }

               $params = array();
               foreach ($vals as $k => $value) {
                       $params[] = $k."=".urlencode($value);
               }
               $result = $beginning . (count($params) ? '?' . implode("&", $params) : '');
               return $result;
       }
kjensen at nospam dot iaff106 dot com
27-Sep-2006 01:21
Here is a simple extended version of ParseURL(). 
I needed to make a link that will be saved off site but point to different file
than the one creating the link.

So I needed to get the path without the file name so I could change the
 file name.

Here it is:

<?php
function ParseURLplus($url){
$URLpcs = (parse_url($url));
$PathPcs = explode("/",$URLpcs['path']);
$URLpcs['file'] = end($PathPcs);
unset(
$PathPcs[key($PathPcs)]);
$URLpcs['dir'] = implode("/",$PathPcs);
return (
$URLpcs);
}

$url = 'http://username:password@hostname/path/directory/file.php?arg=
value#anchor'
;

$URLpcs = ParseURLplus($url);

print_r($URLpcs);
?>

Now I can change the $URLpcs['file'] and then glue itback together to make
 a new url.
corgilabs at SPAM_NO_THANK_YOUgmail dot com
13-Jul-2006 08:59
I hope this is helpful! Cheers!
-eo

<?

# Author: Eric O
# Date: July 13, 2006
# Go Zizou!! :O)

# Creating Automatic Self-Redirect To Secure Version
# of Website as Seen on Paypal and other secure sites
# Changes HTTP to HTTPS

#gets the URI of the script
$url $_SERVER['SCRIPT_URI'];

#chops URI into bits BORK BORK BORK
$chopped = parse_url($url);

#HOST and PATH portions of your final destination
$destination = $chopped[host].$chopped[path];

#if you are not HTTPS, then do something about it
if($chopped[scheme] != "https"){

#forwards to HTTP version of URI with secure certificate
header("Location: https://$destination");

exit();

}

?>
php dot net at NOSPAM dot juamei dot com
09-May-2006 01:18
Modfied version of glue_url to avoid error messages if the error_reporting is set high.

function glue_url($parsed)
{
    if (! is_array($parsed)) return false;
        $uri = isset($parsed['scheme']) ? $parsed['scheme'].':'.((strtolower($parsed['scheme']) == 'mailto') ? '':'//'): '';
        $uri .= isset($parsed['user']) ? $parsed['user'].($parsed['pass']? ':'.$parsed['pass']:'').'@':'';
        $uri .= isset($parsed['host']) ? $parsed['host'] : '';
        $uri .= isset($parsed['port']) ? ':'.$parsed['port'] : '';
        $uri .= isset($parsed['path']) ? $parsed['path'] : '';
        $uri .= isset($parsed['query']) ? '?'.$parsed['query'] : '';
        $uri .= isset($parsed['fragment']) ? '#'.$parsed['fragment'] : '';
    return $uri;
}
TheShadow
30-Dec-2004 09:36
You may want to check out the PEAR NET_URL class. It provides easy means to manipulate URL strings.

http://pear.php.net/package/Net_URL
matt at cryptography dot com
09-May-2004 10: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;
}
?>

rawurldecode> <http_build_query
Last updated: Fri, 18 May 2012