URL - Get the last part in PHP

I have url:

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

and I want the last part of the url:

  gallery_bg.php 

but I do not want to bind statics i.e. for every page that vistitar i want to get the last part of the url

+7
html url php regex
source share
8 answers

use the following

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

Use base name function

 echo basename("http://domain/fotografo/admin/gallery_bg.php"); 
+10
source share
  $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 
+4
source share

If this is the same page:

 echo $_SERVER["REQUEST_URI"]; or echo $_SERVER["SCRIPT_NAME"]; or echo $_SERVER["PHP_SELF"]; 

In each case, a backslash will appear ( / gallery_bg.php). You can crop it like

 echo trim($_SERVER["REQUEST_URI"],"/"); 

or split url by / to create an array and get the last element from the array

 $array = explode("/",$url); $last_item_index = count($url) - 1; echo $array[$last_item_index]; 

or

 echo basename($url); 
+4
source share

Try the following:

 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"); 

- Thanks

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

you can use the basename function ($ url) as suggested above. This returns the file name from the URL. You can also provide the file extension as the second argument to this function, for example basename ($ url, '.jpg'), after which the file name without the extension will be displayed.

For example:

 $url = "https://i0.com/images/test.jpg" then echo basename($url) will print test.jpg and echo basename($url,".jpg") will print test 
0
source share
  $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, '/'); 

In PHP 7, the decision made gives me the error that only variables are allowed, so this works for me.

0
source share

All Articles