Wie kann man mit PHP den relativen Pfad in eine absolute URL umwandeln?
Wandeln Sie mithilfe von PHP den relativen Pfad in eine absolute URL um
Paul
bimbo22
function rel2abs($rel, $base)
{
/* return if already absolute URL */
if (parse_url($rel, PHP_URL_SCHEME) != '') return $rel;
/* queries and anchors */
if ($rel[0]=='#' || $rel[0]=='?') return $base.$rel;
/* parse base URL and convert to local variables:
$scheme, $host, $path */
extract(parse_url($base));
/* remove non-directory element from path */
$path = preg_replace('#/[^/]*$#', '', $path);
/* destroy path if relative url points to root */
if ($rel[0] == "https://stackoverflow.com/") $path="";
/* dirty absolute URL */
$abs = "$host$path/$rel";
/* replace '//' or '/./' or '/foo/../' with "https://stackoverflow.com/" */
$re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
for($n=1; $n>0; $abs=preg_replace($re, "https://stackoverflow.com/", $abs, -1, $n)) {}
/* absolute URL is ready! */
return $scheme.'://'.$abs;
}
-
Das ist meistens gut genug, aber es scheitert in vielen Grenzfällen.
– pguardiario
24. Juli 2013 um 23:44 Uhr
-
wenn die relative URL mit ? Es sollte den Abfrageteil aus der Basis entfernen, bevor relative und absolute URLs aufgeteilt werden
– Qdinar
3. Januar 2016 um 15:48 Uhr
-
Ist nicht
$rel
soll ein String mit der relativen URL sein? Warum versuchst du es$rel[0]
? Es gibt nur einen Fehler zurückUninitialized string offset: 0
.– Helfende Hand
27. Januar 2016 um 18:46 Uhr
-
Dieser Link ist jetzt tot; führt zu einer illegalen Website (wahrscheinlich Malware)
– Lukas Taylor
3. März 2016 um 22:58 Uhr
-
schlägt fehl, wenn rel mit “//” beginnt
– dlnh
25. Februar 2018 um 14:55 Uhr
Ich liebe den Code, den jordanstephens über den Link bereitgestellt hat! Ich habe dafür gestimmt. l0oky hat mich dazu inspiriert sicherzustellen, dass die Funktion mit Port, Benutzername und Passwort-URL kompatibel ist. Ich brauchte es für mein Projekt.
function rel2abs( $rel, $base )
{
/* return if already absolute URL */
if( parse_url($rel, PHP_URL_SCHEME) != '' )
return( $rel );
/* queries and anchors */
if( $rel[0]=='#' || $rel[0]=='?' )
return( $base.$rel );
/* parse base URL and convert to local variables:
$scheme, $host, $path */
extract( parse_url($base) );
/* remove non-directory element from path */
$path = preg_replace( '#/[^/]*$#', '', $path );
/* destroy path if relative url points to root */
if( $rel[0] == "https://stackoverflow.com/" )
$path="";
/* dirty absolute URL */
$abs="";
/* do we have a user in our URL? */
if( isset($user) )
{
$abs.= $user;
/* password too? */
if( isset($pass) )
$abs.= ':'.$pass;
$abs.= '@';
}
$abs.= $host;
/* did somebody sneak in a port? */
if( isset($port) )
$abs.= ':'.$port;
$abs.=$path."https://stackoverflow.com/".$rel;
/* replace '//' or '/./' or '/foo/../' with "https://stackoverflow.com/" */
$re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
for( $n=1; $n>0; $abs=preg_replace( $re, "https://stackoverflow.com/", $abs, -1, $n ) ) {}
/* absolute URL is ready! */
return( $scheme.'://'.$abs );
}
-
aber es wird den absoluten Dateisystempfad zurückgeben und wir wollen die absolute URL
– siddhesch
9. März 2015 um 6:30 Uhr
-
Dies sollte eine URL zurückgeben. Gibt es einen Dateipfad für Sie zurück?
– Mikey A. Leonetti
27. März 2015 um 18:34 Uhr
Unterstützung hinzugefügt, um die aktuelle Abfrage beizubehalten. Hilft sehr für ?page=1 und so weiter…
function rel2abs($rel, $base)
{
/* return if already absolute URL */
if (parse_url($rel, PHP_URL_SCHEME) != '')
return ($rel);
/* queries and anchors */
if ($rel[0] == '#' || $rel[0] == '?')
return ($base . $rel);
/* parse base URL and convert to local variables: $scheme, $host, $path, $query, $port, $user, $pass */
extract(parse_url($base));
/* remove non-directory element from path */
$path = preg_replace('#/[^/]*$#', '', $path);
/* destroy path if relative url points to root */
if ($rel[0] == "https://stackoverflow.com/")
$path="";
/* dirty absolute URL */
$abs="";
/* do we have a user in our URL? */
if (isset($user)) {
$abs .= $user;
/* password too? */
if (isset($pass))
$abs .= ':' . $pass;
$abs .= '@';
}
$abs .= $host;
/* did somebody sneak in a port? */
if (isset($port))
$abs .= ':' . $port;
$abs .= $path . "https://stackoverflow.com/" . $rel . (isset($query) ? '?' . $query : '');
/* replace '//' or '/./' or '/foo/../' with "https://stackoverflow.com/" */
$re = ['#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#'];
for ($n = 1; $n > 0; $abs = preg_replace($re, "https://stackoverflow.com/", $abs, -1, $n)) {
}
/* absolute URL is ready! */
return ($scheme . '://' . $abs);
}
-
schlägt auch fehl für rel beginnend mit “//”
– dlnh
25. Februar 2018 um 14:57 Uhr
Diblo Dk
Ein Webbrowser verwendet die Seiten-URL oder die Basis-Tag um relative URLs aufzulösen.
Dieses Skript kann eine URL relativ zu einer Basis-URL auflösen.
/** Build a URL
*
* @param array $parts An array that follows the parse_url scheme
* @return string
*/
function build_url(array $parts): string
{
$url = $parts['scheme'] . '://';
if (!empty($parts['user'])) {
$url .= $parts['user'];
}
if (!empty($parts['pass'])) {
$url .= ':' . $parts['pass'];
}
if (!empty($parts['user'])) {
$url .= '@';
}
$url .= $parts['host'];
if (!empty($parts['port'])) {
$url .= ':' . $parts['port'];
}
if (!empty($parts['path'])) {
$url .= $parts['path'];
}
if (!empty($parts['query'])) {
$url .= '?' . $parts['query'];
}
if (!empty($parts['fragment'])) {
$url .= '#' . $parts['fragment'];
}
return $url;
}
/** Convert a relative path in to an absolute path
*
* @param string $path
* @return string
*/
function abs_path(string $path): string
{
$path_array = explode("https://stackoverflow.com/", $path);
// Solve current and parent folder navigation
$abs_path_array = array();
foreach ($path_array as $name) {
if (empty($name)) {
continue;
}
if ($name == '..') {
array_pop($abs_path_array);
} elseif ($name != '.') {
$abs_path_array[] = $name;
}
}
return "https://stackoverflow.com/" . implode("https://stackoverflow.com/", $abs_path_array);
}
/** Convert a relative URL in to an absolute URL
*
* @param string $url URL or URI
* @param string $base Absolute URL
* @return string
*/
function abs_url(string $url, string $base): string
{
$url_parts = parse_url($url);
$base_parts = parse_url($base);
// Handle the path if it is specified
if (!empty($url_parts['path'])) {
// Is the path relative
if (!str_starts_with($url_parts['path'], "https://stackoverflow.com/")) {
if (str_ends_with($base_parts['path'], "https://stackoverflow.com/")) {
$url_parts['path'] = $base_parts['path'] . $url_parts['path'];
} else {
$url_parts['path'] = dirname($base_parts['path']) . "https://stackoverflow.com/" . $url_parts['path'];
}
}
// Make path absolute
$url_parts['path'] = abs_path($url_parts['path']);
}
// Use the base URL to populate the unfilled components until a component is filled
foreach (['scheme', 'host', 'path', 'query', 'fragment'] as $comp) {
if (!empty($url_parts[$comp])) {
break;
}
$url_parts[$comp] = $base_parts[$comp];
}
return build_url($url_parts);
}
Prüfen
// Base URL
$base_url="https://example.com/path1/path2/path3/path4/file.ext?field1=value1&field2=value2#fragment";
// URL and URIs (_ is used to see what is coming from relative URL)
$test_urls = array(
"http://_example.com/_path1/_path2/_file.ext?_field1=_value1&_field2=_value2#_fragment", // URL
"//_example.com/_path1/_path2/_file.ext?_field1=_value1&_field2=_value2#_fragment", // URI without scheme
"//_example.com", // URI with host only
"/_path1/_path2/_file.ext?_field1=_value1&_field2=_value2#_fragment", // URI without scheme and host
"_path1/_path2/_file.ext", // URI with path only
"./../../_path1/../_path2/file.ext#_fragment", // URI with path and fragment
"?_field1=_value1&_field2=_value2#_fragment", // URI with query and fragment
"#_fragment" // URI with fragment only
);
// Expected result
$expected_urls = array(
"http://_example.com/_path1/_path2/_file.ext?_field1=_value1&_field2=_value2#_fragment",
"https://_example.com/_path1/_path2/_file.ext?_field1=_value1&_field2=_value2#_fragment",
"https://_example.com",
"https://example.com/_path1/_path2/_file.ext?_field1=_value1&_field2=_value2#_fragment",
"https://example.com/path1/path2/path3/path4/_path1/_path2/_file.ext",
"https://example.com/path1/path2/_path2/file.ext#_fragment",
"https://example.com/path1/path2/path3/path4/file.ext?_field1=_value1&_field2=_value2#_fragment",
"https://example.com/path1/path2/path3/path4/file.ext?field1=value1&field2=value2#_fragment"
);
foreach ($test_urls as $i => $url) {
$abs_url = abs_url($url, $base_url);
if ( $abs_url == $expected_urls[$i] ) {
echo "[OK] " . $abs_url . PHP_EOL;
} else {
echo "[WRONG] " . $abs_url . PHP_EOL;
}
}
Ergebnis
[OK] http://_example.com/_path1/_path2/_file.ext?_field1=_value1&_field2=_value2#_fragment
[OK] https://_example.com/_path1/_path2/_file.ext?_field1=_value1&_field2=_value2#_fragment
[OK] https://_example.com
[OK] https://example.com/_path1/_path2/_file.ext?_field1=_value1&_field2=_value2#_fragment
[OK] https://example.com/path1/path2/path3/path4/_path1/_path2/_file.ext
[OK] https://example.com/path1/path2/_path2/file.ext#_fragment
[OK] https://example.com/path1/path2/path3/path4/file.ext?_field1=_value1&_field2=_value2#_fragment
[OK] https://example.com/path1/path2/path3/path4/file.ext?field1=value1&field2=value2#_fragment
s3v3n
War nicht tatsächlich die Frage nach dem Konvertieren des Pfads und nicht der URL? PHP hat dafür tatsächlich eine Funktion: realpath(). Das einzige, was Sie beachten sollten, sind Symlinks.
Beispiel aus dem PHP-Handbuch:
chdir('/var/www/');
echo realpath('./../../etc/passwd') . PHP_EOL;
// Prints: /etc/passwd
echo realpath('/tmp/') . PHP_EOL;
// Prints: /tmp
-
Können Sie ein Beispiel für die Verwendung geben?
– Nik
20. Juli 2016 um 1:10 Uhr
-
Das Ergebnis dieser Methode ist ein Pfad und keine URL. Die Frage fragt nach URL.
– Moradnejad
7. Juni 2017 um 6:41 Uhr
javon27
Ich habe die Funktion aktualisiert, um die relative URL zu korrigieren, die mit „//“ beginnt, um die Ausführungsgeschwindigkeit zu verbessern.
function getAbsoluteUrl($relativeUrl, $baseUrl){
// if already absolute URL
if (parse_url($relativeUrl, PHP_URL_SCHEME) !== null){
return $relativeUrl;
}
// queries and anchors
if ($relativeUrl[0] === '#' || $relativeUrl[0] === '?'){
return $baseUrl.$relativeUrl;
}
// parse base URL and convert to: $scheme, $host, $path, $query, $port, $user, $pass
extract(parse_url($baseUrl));
// if base URL contains a path remove non-directory elements from $path
if (isset($path) === true){
$path = preg_replace('#/[^/]*$#', '', $path);
}
else {
$path="";
}
// if realtive URL starts with //
if (substr($relativeUrl, 0, 2) === '//'){
return $scheme.':'.$relativeUrl;
}
// if realtive URL starts with /
if ($relativeUrl[0] === "https://stackoverflow.com/"){
$path = null;
}
$abs = null;
// if realtive URL contains a user
if (isset($user) === true){
$abs .= $user;
// if realtive URL contains a password
if (isset($pass) === true){
$abs .= ':'.$pass;
}
$abs .= '@';
}
$abs .= $host;
// if realtive URL contains a port
if (isset($port) === true){
$abs .= ':'.$port;
}
$abs .= $path."https://stackoverflow.com/".$relativeUrl.(isset($query) === true ? '?'.$query : null);
// replace // or /./ or /foo/../ with /
$re = ['#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#'];
for ($n = 1; $n > 0; $abs = preg_replace($re, "https://stackoverflow.com/", $abs, -1, $n)) {
}
// return absolute URL
return $scheme.'://'.$abs;
}
-
Können Sie ein Beispiel für die Verwendung geben?
– Nik
20. Juli 2016 um 1:10 Uhr
-
Das Ergebnis dieser Methode ist ein Pfad und keine URL. Die Frage fragt nach URL.
– Moradnejad
7. Juni 2017 um 6:41 Uhr
function url_to_absolute($baseURL, $relativeURL) {
$relativeURL_data = parse_url($relativeURL);
if (isset($relativeURL_data['scheme'])) {
return $relativeURL;
}
$baseURL_data = parse_url($baseURL);
if (!isset($baseURL_data['scheme'])) {
return $relativeURL;
}
$absoluteURL_data = $baseURL_data;
if (isset($relativeURL_data['path']) && $relativeURL_data['path']) {
if (substr($relativeURL_data['path'], 0, 1) == "https://stackoverflow.com/") {
$absoluteURL_data['path'] = $relativeURL_data['path'];
} else {
$absoluteURL_data['path'] = (isset($absoluteURL_data['path']) ? preg_replace('#[^/]*$#', '', $absoluteURL_data['path']) : "https://stackoverflow.com/") . $relativeURL_data['path'];
}
if (isset($relativeURL_data['query'])) {
$absoluteURL_data['query'] = $relativeURL_data['query'];
} else if (isset($absoluteURL_data['query'])) {
unset($absoluteURL_data['query']);
}
} else {
$absoluteURL_data['path'] = isset($absoluteURL_data['path']) ? $absoluteURL_data['path'] : "https://stackoverflow.com/";
if (isset($relativeURL_data['query'])) {
$absoluteURL_data['query'] = $relativeURL_data['query'];
} else if (isset($absoluteURL_data['query'])) {
$absoluteURL_data['query'] = $absoluteURL_data['query'];
}
}
if (isset($relativeURL_data['fragment'])) {
$absoluteURL_data['fragment'] = $relativeURL_data['fragment'];
} else if (isset($absoluteURL_data['fragment'])) {
unset($absoluteURL_data['fragment']);
}
$absoluteURL_path = ltrim($absoluteURL_data['path'], "https://stackoverflow.com/");
$absoluteURL_path_parts = array();
for ($i = 0, $i2 = 0; $i < strlen($absoluteURL_path); $i++) {
if (isset($absoluteURL_path_parts[$i2])) {
$absoluteURL_path_parts[$i2] .= $absoluteURL_path[$i];
} else {
$absoluteURL_path_parts[$i2] = $absoluteURL_path[$i];
}
if ($absoluteURL_path[$i] == "https://stackoverflow.com/") {
$i2++;
}
}
reset($absoluteURL_path_parts);
while (true) {
if (rtrim(current($absoluteURL_path_parts), "https://stackoverflow.com/") == '.') {
unset($absoluteURL_path_parts[key($absoluteURL_path_parts)]);
continue;
} else if (rtrim(current($absoluteURL_path_parts), "https://stackoverflow.com/") == '..') {
if (prev($absoluteURL_path_parts) !== false) {
unset($absoluteURL_path_parts[key($absoluteURL_path_parts)]);
} else {
reset($absoluteURL_path_parts);
}
unset($absoluteURL_path_parts[key($absoluteURL_path_parts)]);
continue;
}
if (next($absoluteURL_path_parts) === false) {
break;
}
}
$absoluteURL_data['path'] = "https://stackoverflow.com/" . implode('', $absoluteURL_path_parts);
$absoluteURL = isset($absoluteURL_data['scheme']) ? $absoluteURL_data['scheme'] . ':' : '';
$absoluteURL .= (isset($absoluteURL_data['user']) || isset($absoluteURL_data['host'])) ? '//' : '';
$absoluteURL .= isset($absoluteURL_data['user']) ? $absoluteURL_data['user'] : '';
$absoluteURL .= isset($absoluteURL_data['pass']) ? ':' . $absoluteURL_data['pass'] : '';
$absoluteURL .= isset($absoluteURL_data['user']) ? '@' : '';
$absoluteURL .= isset($absoluteURL_data['host']) ? $absoluteURL_data['host'] : '';
$absoluteURL .= isset($absoluteURL_data['port']) ? ':' . $absoluteURL_data['port'] : '';
$absoluteURL .= isset($absoluteURL_data['path']) ? $absoluteURL_data['path'] : '';
$absoluteURL .= isset($absoluteURL_data['query']) ? '?' . $absoluteURL_data['query'] : '';
$absoluteURL .= isset($absoluteURL_data['fragment']) ? '#' . $absoluteURL_data['fragment'] : '';
return $absoluteURL;
}
-
Es gibt andere Antworten, die die Frage des OP liefern, und sie wurden vor vielen Jahren veröffentlicht. Stellen Sie beim Posten einer Antwort bitte sicher, dass Sie entweder eine neue Lösung oder eine wesentlich bessere Erklärung hinzufügen, insbesondere wenn Sie ältere Fragen beantworten.
– help-info.de
7. Mai 2019 um 18:10 Uhr
Duplikate: stackoverflow.com/questions/19618754/… , stackoverflow.com/questions/26423904/…
– Qdinar
3. Januar 2016 um 15:52 Uhr
ein weiteres Duplikat: stackoverflow.com/questions/11653677/…
– Qdinar
3. Januar 2016 um 15:58 Uhr
Diese Frage selbst ist ein Duplikat von stackoverflow.com/questions/1243418/…
– Qdinar
3. Januar 2016 um 16:02 Uhr
@qdinar duplizieren->duplizieren 🙂
– Gasser
14. Januar 2018 um 5:40 Uhr