在PHP中获取URL的最后一部分

28

我有我的URL:

http://domain/fotografo/admin/gallery_bg.php

我想要URL的最后一部分:

 gallery_bg.php

但是,我不想链接静态页面,也就是说,对于每个访问者访问的页面,我想获取URL的最后一部分。

8个回答

38

使用 basename 函数

echo basename("http://domain/fotografo/admin/gallery_bg.php");

1
这非常高效和快速。 - farhang
@farhang 这取决于你想要它做什么。对我来说,$_SERVER["REQUEST_URI"]是我所需的... - Thanasis
对我来说起作用了,因为“验证答案”没有,因为我的链接最后以“/”结束,而我需要最后一个元素,无论是否存在。谢谢! - maiakd

38

请使用以下内容

<?php
    $link = $_SERVER['PHP_SELF'];
    $link_array = explode('/',$link);
    echo $page = end($link_array);
?>

没能成功是因为我的链接最后带了一个 /,例如:https/mysite.com/products/my-name/。我尝试了@jaydeep在这里提供的“basename”解决方案,它更快且完美地解决了问题! - maiakd
没起作用是因为我的链接最后带了一个斜杠,例如:**https/mysite.com/products/my-name/**。我尝试了@jaydeep在这里提供的解决方案,使用"basename"函数,速度更快且完美运行! - undefined

11

如果是同一页:

echo $_SERVER["REQUEST_URI"];

or

echo $_SERVER["SCRIPT_NAME"];

or 

echo $_SERVER["PHP_SELF"];

在每种情况下,都会出现一个反斜杠(/gallery_bg.php)。您可以将其删除。


echo trim($_SERVER["REQUEST_URI"],"/");
或者按照/分割链接并将其转换为数组,然后获取数组中的最后一项。
$array = explode("/",$url);

$last_item_index = count($url) - 1;

echo $array[$last_item_index];
或者
echo basename($url);

如果您将URI编写为"https//server/myscript",并且它通过.htaccess重定向到"https//server/some.php",那么唯一能够正常工作并返回"myscript"的是$_SERVER["REQUEST_URI"],其他建议将返回"some.php"。 - Thanasis

7
 $url = "http://domain/fotografo/admin/gallery_bg.php";
 $keys = parse_url($url); // parse the url
 $path = explode("/", $keys['path']); // splitting the path
 $last = end($path); // get the value of the last element 

6
您可以像上面建议的那样使用basename($url)函数。这将从URL中返回文件名。您还可以将文件扩展名作为第二个参数提供给此函数,例如basename($url, '.jpg'),然后将返回不带扩展名的文件名。
例如:

$url = "https://i0.com/images/test.jpg"

then echo basename($url) will print test.jpg

and echo basename($url,".jpg") will print test


1

试试这个:

Here you have 2 options.

1. Using explode function.

$filename = end(explode('/', 'http://domain/fotografo/admin/gallery_bg.php'));

2. Use basename function.

$filename = basename("http://domain/fotografo/admin/gallery_bg.php");

- 谢谢


1
$url  = $_SERVER["PHP_SELF"];
$path = explode("/", $url); 
$last = end($path);

0
    $basepath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
    $uri = substr($_SERVER['REQUEST_URI'], strlen($basepath));
    if (strstr($uri, '?')) $uri = substr($uri, 0, strpos($uri, '?'));
    $url = trim($uri, '/');

在 PHP 7 中,接受的解决方案给我一个错误,即在 explode 中只允许使用变量,所以这对我有效。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接