parts - url param php
Holen Sie sich die vollständige URL in PHP (18)
Kurze Version zum Ausgeben eines Links auf einer Webseite
$url = "//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$escaped_url = htmlspecialchars( $url, ENT_QUOTES, 'UTF-8' );
echo '<a href="' . $escaped_url . '">' . $escaped_url . '</a>';
Im Folgenden finden Sie weitere Informationen zu den Problemen und Randfällen im Format //example.com/path/
Vollversion
function url_origin( $s, $use_forwarded_host = false )
{
$ssl = ( ! empty( $s['HTTPS'] ) && $s['HTTPS'] == 'on' );
$sp = strtolower( $s['SERVER_PROTOCOL'] );
$protocol = substr( $sp, 0, strpos( $sp, '/' ) ) . ( ( $ssl ) ? 's' : '' );
$port = $s['SERVER_PORT'];
$port = ( ( ! $ssl && $port=='80' ) || ( $ssl && $port=='443' ) ) ? '' : ':'.$port;
$host = ( $use_forwarded_host && isset( $s['HTTP_X_FORWARDED_HOST'] ) ) ? $s['HTTP_X_FORWARDED_HOST'] : ( isset( $s['HTTP_HOST'] ) ? $s['HTTP_HOST'] : null );
$host = isset( $host ) ? $host : $s['SERVER_NAME'] . $port;
return $protocol . '://' . $host;
}
function full_url( $s, $use_forwarded_host = false )
{
return url_origin( $s, $use_forwarded_host ) . $s['REQUEST_URI'];
}
$absolute_url = full_url( $_SERVER );
echo $absolute_url;
Dies ist eine stark modifizierte Version von http://snipplr.com/view.php?codeview&id=2734
.
URL-Struktur:
Schema: // Benutzername: Passwort @Domain: Port / Pfad? Query_String # Fragment_ID
Die fett gedruckten Teile werden von der Funktion nicht berücksichtigt
Anmerkungen:
- Diese Funktion enthält nicht den
username:password
von einer vollständigen URL oder das Fragment (Hash). - Der Standardport 80 für HTTP und Port 443 für HTTPS wird nicht angezeigt.
- Nur getestet mit http und https Schemata.
- Die
#fragment_id
wird nicht vom Client (Browser) an den Server gesendet und nicht zur vollständigen URL hinzugefügt. -
$_GET
enthält nurfoo=bar2
für eine URL wie/example?foo=bar1&foo=bar2
. - Einige CMS und Umgebungen schreiben
$_SERVER['REQUEST_URI']
und geben/example?foo=bar2
für eine URL wie/example?foo=bar1&foo=bar2
, verwenden$_SERVER['QUERY_STRING']
in diesem Fall$_SERVER['QUERY_STRING']
. - Denken Sie daran, dass ein URI =
URL + URN
, aber aufgrund der weit verbreiteten Verwendung bedeutet URL jetzt sowohl URI als auch URL. - Sie sollten
HTTP_X_FORWARDED_HOST
entfernen, wenn Sie keine Proxies oder Balancers verwendenHTTP_X_FORWARDED_HOST
. - Die spec besagt, dass der
Host
Header die Portnummer enthalten muss, sofern es sich nicht um die Standardnummer handelt.
Vom Client (Browser) gesteuerte Variablen:
-
$_SERVER['REQUEST_URI']
. Nicht unterstützte Zeichen werden vor dem Senden vom Browser verschlüsselt. -
$_SERVER['HTTP_HOST']
und ist laut den Kommentaren im PHP-Handbuch nicht immer verfügbar: http://php.net/manual/en/reserved.variables.php -
$_SERVER['HTTP_X_FORWARDED_HOST']
wird von Balancern gesetzt und wird nicht in der Liste der$_SERVER
Variablen im PHP Handbuch erwähnt.
Servergesteuerte Variablen:
-
$_SERVER['HTTPS']
. Der Client wählt dies, aber der Server gibt den tatsächlichen Wert entweder leer oder "an" zurück. -
$_SERVER['SERVER_PORT']
. Der Server akzeptiert nur erlaubte Nummern als Ports. -
$_SERVER['SERVER_PROTOCOL']
. Der Server akzeptiert nur bestimmte Protokolle. -
$_SERVER['SERVER_NAME']
Sie wird in der Serverkonfiguration manuell festgelegt und ist laut kralyk nicht für IPv6 kralyk .
Verbunden:
HTTP_HOST vs. SERVER_NAME
Ist die Portnummer im Header-Parameter "Host" von HTTP erforderlich?
https://stackoverflow.com/a/28049503/175071
Ich verwende diesen Code, um die vollständige URL zu erhalten:
$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
Das Problem ist, dass ich einige Masken in meinem .htaccess
, also was wir in der URL sehen, ist nicht immer der wirkliche Pfad der Datei.
Was ich brauche ist, um die URL zu erhalten, was in der URL geschrieben ist, nicht mehr und nicht weniger - die vollständige URL.
Ich muss herausfinden, wie es in der Navigationsleiste im Webbrowser angezeigt wird, und nicht den tatsächlichen Pfad der Datei auf dem Server.
Beispiele für URL: https://example.com/subFolder/yourfile.php?var=blabla#12345
typische PHP-Codes:
//built-in function
$x = parse_url($url);
$x['scheme'] 🡺 https
$x['host'] 🡺 example.com (or with WWW)
$x['path'] 🡺 /subFolder/yourfile.php
$x['query'] 🡺 var=blabla
$x['fragment'] 🡺 12345 // hashtag outputed only in case, when hashtag-containing string was manually passed to function, otherwise PHP is unable to recognise hashtags in $_SERVER
//built-in function (with this function, I only recommend to pass `parse_url`s output as argument)
$A = pathinfo($url);
$B = pathinfo(parse_url($url)['path']);
$A['dirname'] 🡺 https://example.com/subFolder
$B['dirname'] 🡺 /subFolder
$A['basename'] 🡺 yourfile.php?var=blabla#12345
$B['basename'] 🡺 yourfile.php
$A['extension'] 🡺 php?var=blabla#12345
$B['extension'] 🡺 php
$A['filename'] 🡺 yourfile
$B['filename'] 🡺 yourfile
//=================================================== //
//========== self-defined SERVER variables ========== //
//=================================================== //
$_SERVER["DOCUMENT_ROOT"] 🡺 /home/user/public_html
$_SERVER["SERVER_ADDR"] 🡺 143.34.112.23
$_SERVER["SERVER_PORT"] 🡺 80(or 443 etc..)
$_SERVER["REQUEST_SCHEME"] 🡺 https //similar: $_SERVER["SERVER_PROTOCOL"]
$_SERVER['HTTP_HOST'] 🡺 example.com (or with WWW) //similar: $_SERVER["ERVER_NAME"]
$_SERVER["REQUEST_URI"] 🡺 /subFolder/yourfile.php?var=blabla
$_SERVER["QUERY_STRING"] 🡺 var=blabla
__FILE__ 🡺 /home/user/public_html/subFolder/yourfile.php
__DIR__ 🡺 /home/user/public_html/subFolder //same: dirname(__FILE__)
$_SERVER["REQUEST_URI"] 🡺 /subFolder/yourfile.php?var=blabla
parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH)🡺 /subFolder/yourfile.php
$_SERVER["PHP_SELF"] 🡺 /subFolder/yourfile.php
// ==================================================================//
//if "YOURFILE.php" is included in "PARENTFILE.php" , and you visit "PARENTFILE.PHP?abc":
$_SERVER["SCRIPT_FILENAME"]🡺 /home/user/public_html/parentfile.php
$_SERVER["PHP_SELF"] 🡺 /parentfile.php
$_SERVER["REQUEST_URI"] 🡺 /parentfile.php?abc
__FILE__ 🡺 /home/user/public_html/subFolder/yourfile.php
// =================================================== //
// ================= handy variables ================= //
// =================================================== //
//If site uses HTTPS:
$HTTP_or_HTTPS = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off') || $_SERVER['SERVER_PORT']==443) ? 'https://':'http://' ); //in some cases, you need to add this condition too: if ('https'==$_SERVER['HTTP_X_FORWARDED_PROTO']) ...
//To trim values to filename, i.e.
basename($url) 🡺 yourfile.php
//excellent solution to find origin
$debug_files = debug_backtrace(); $initial_called_file = count($debug_files) ? $debug_files[count($debug_files) - 1]['file'] : __FILE__;
Beachten!:
- hastag (# ...) URL Teile können nicht von PHP (serverseitig) erkannt werden. Verwenden Sie dazu Javascript.
-
DIRECTORY_SEPARATOR
gibt\
für Windows-Host-Typen anstelle von/
.
Für WordPress
//(let's say, if wordpress is installed in subdirectory: http://example.com/wpdir/)
home_url() 🡺 http://example.com/wpdir/ //if is_ssl() is true, then it will be "https"
get_stylesheet_directory_uri() 🡺 http://example.com/wpdir/wp-content/themes/THEME_NAME [same: get_bloginfo('template_url') ]
get_stylesheet_directory() 🡺 /home/user/public_html/wpdir/wp-content/themes/THEME_NAME
plugin_dir_url(__FILE__) 🡺 http://example.com/wpdir/wp-content/themes/PLUGIN_NAME
plugin_dir_path(__FILE__) 🡺 /home/user/public_html/wpdir/wp-content/plugins/PLUGIN_NAME/
Einfach verwenden:
$uri = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
Gleiche Technik wie die angenommene Antwort, aber mit HTTPS Unterstützung und besser lesbar:
$current_url = sprintf(
'%s://%s/%s',
isset($_SERVER['HTTPS']) ? 'https' : 'http',
$_SERVER['HTTP_HOST'],
$_SERVER['REQUEST_URI']
);
Hier ist meine Lösung - der Code wurde von Tracy Debugger inspiriert. Es wurde geändert, um verschiedene Serverports zu unterstützen. Sie können die vollständige aktuelle URL einschließlich $_SERVER['REQUEST_URI']
oder nur die grundlegende Server-URL $_SERVER['REQUEST_URI']
. Prüfe meine Funktion:
function getCurrentUrl($full = true) {
if (isset($_SERVER['REQUEST_URI'])) {
$parse = parse_url(
(isset($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'off') ? 'https://' : 'http://') .
(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '')) . (($full) ? $_SERVER['REQUEST_URI'] : null)
);
$parse['port'] = $_SERVER["SERVER_PORT"]; // Setup protocol for sure (80 is default)
return http_build_url('', $parse);
}
}
Hier ist der Testcode:
// Follow $_SERVER variables was set only for test
$_SERVER['HTTPS'] = 'off'; // on
$_SERVER['SERVER_PORT'] = '9999'; // Setup
$_SERVER['HTTP_HOST'] = 'some.crazy.server.5.name:8088'; // Port is optional there
$_SERVER['REQUEST_URI'] = '/150/tail/single/normal?get=param';
echo getCurrentUrl();
// http://some.crazy.server.5.name:9999/150/tail/single/normal?get=param
echo getCurrentUrl(false);
// http://some.crazy.server.5.name:9999/
Ich habe diese Funktion gemacht, um die URL zu behandeln:
<?php
function curPageURL()
{
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .=
$_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
?>
Meine bevorzugte Cross-Plattform-Methode zum Auffinden der aktuellen URL ist:
$url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
Schauen Sie sich $_SERVER['REQUEST_URI']
, d
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
(Beachten Sie, dass die String-Syntax in doppelten Anführungszeichen vollkommen korrekt ist )
Wenn Sie sowohl HTTP als auch HTTPS unterstützen möchten, können Sie verwenden
$actual_link = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
Anmerkung des Herausgebers: Die Verwendung dieses Codes hat Auswirkungen auf die Sicherheit . Der Client kann HTTP_HOST und REQUEST_URI auf einen beliebigen beliebigen Wert setzen.
Versuche dies:
$pageURL = $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
$pageURL .= $_SERVER['SERVER_PORT'] != '80' ? $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"] : $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
echo $pageURL;
Versuche dies:
print_r($_SERVER);
$_SERVER
is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the » CGI/1.1 specification, so you should be able to expect those.
$HTTP_SERVER_VARS
contains the same initial information, but is not a superglobal. (Note that $HTTP_SERVER_VARS
and $_SERVER
are different variables and that PHP handles them as such)
Dies funktioniert sowohl für HTTP als auch für HTTPS.
echo 'http' . (($_SERVER['HTTPS'] == 'on') ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
Gib so etwas aus.
https://example.com/user.php?token=3f0d9sickc0flmg8hnsngk5u07&access_level=application
I have used the below code, and it is working fine for me, for both cases, HTTP and HTTPS.
function curPageURL() {
if(isset($_SERVER["HTTPS"]) && !empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] != 'on' )) {
$url = 'https://'.$_SERVER["SERVER_NAME"];//https url
} else {
$url = 'http://'.$_SERVER["SERVER_NAME"];//http url
}
if(( $_SERVER["SERVER_PORT"] != 80 )) {
$url .= $_SERVER["SERVER_PORT"];
}
$url .= $_SERVER["REQUEST_URI"];
return $url;
}
echo curPageURL();
I used this statement.
$base = "http://$_SERVER[SERVER_NAME]:$_SERVER[SERVER_PORT]$my_web_base_path";
$url = $base . "/" . dirname(dirname(__FILE__));
I hope this will help you.
This is quite easy to do with your Apache environment variables. This only works with Apache 2, which I assume you are using.
Simply use the following PHP code:
<?php
$request_url = apache_getenv("HTTP_HOST") . apache_getenv("REQUEST_URI");
echo $request_url;
?>
You can make use of HTTP_ORIGIN
as illustrated in the snippet below:
if ( ! array_key_exists( 'HTTP_ORIGIN', $_SERVER ) ) {
$this->referer = $_SERVER['SERVER_NAME'];
} else {
$this->referer = $_SERVER['HTTP_ORIGIN'];
}
You can use http_build_url with no arguments to get the full URI of the current page:
$url = http_build_url();
$page_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
Für mehr: https://codeupweb.wordpress.com/2017/10/11/how-to-get-the-full-url-of-page-using-php/
$url = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
Above line store full URL in the variable $url. It includes https/http, subdomain, domain requested page.