0

I'm having an issue with grabbing the last part of the URL before the query parameters.
The current solution I'm using is this:

$base_url = current_url();
$uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri_segments = explode('/', $uri_path);
$language = $uri_segments[1];
$end_url = array_pop($uri_segments);

I then pass the $end_url through a Switch statement to modify form fields, depending on the value.
Is there something I'm missing or is there a more efficient way to grab the last part of the URL? Any suggestions would be helpful and greatly appreciated.
Thanks!

RichardManson
  • 167
  • 1
  • 1
  • 10
  • You're exploding using `/` as the delimiter. So the query parameters will be included in the last element, since there's no `/` delimiter there. – Barmar May 14 '21 at 02:54
  • You can use `explode('?', $end_url)` and then use the first element of that. – Barmar May 14 '21 at 02:55
  • See https://www.php.net/manual/en/reserved.variables.server.php#120979 maybe you should be using one of the other `$_SERVER` variables, like `PHP_SELF` or `SCRIPT_NAME`. They don't include the query parameters. – Barmar May 14 '21 at 02:59
  • `basename($uri_path)` - https://3v4l.org/pZT83 – Phil May 14 '21 at 03:30

1 Answers1

1

try this

<?php
$url = parse_url('http://example.com/project/controller/action/param1/param2');
$url['sections'] = explode('/', $url['path']);

$last = end($url['sections']);
echo $last;
?>

output

param2

Artier
  • 1,648
  • 2
  • 8
  • 22