2

I've a PHP file. In this file I need to check, if my URL has the following ending:

www.example.de/dashboard/2/

So the ending can be a number 1 - 99+ which is always at the end of the url between two slashes. I can't use $_GET here. If it is $_GET, it would be easy:

if ( isset($_GET['ending']) ) :

So how can I do this without a parameter in the URL? Thanks for your help!

Mr. Jo
  • 3,961
  • 1
  • 22
  • 54

5 Answers5

2
if(preg_match('^\/dashboard\/(\d+)', $_SERVER['REQUEST_URI'])){
    foo();
}

Use regular expression on the request uri

Lenart12
  • 21
  • 4
1

You can make use of parse_url and explode:

$url = 'http://www.example.de/dashboard/2/';

$path = parse_url($url, PHP_URL_PATH); // '/dashboard/2/'
$parts = explode('/', $path);          // ['', 'dashboard', '2', '']
$section = $parts[1];                  // 'dashboard'
$ending = $parts[2];                   // '2'

Demo: https://3v4l.org/dv6Cn

You can also make use of URL rewriting (this is for a Apache-based web server, but you can find simular resources for nginx or any other web servers if need be).

Jeto
  • 13,447
  • 2
  • 22
  • 39
1

A more dynamic way is to explode and use array_filter to remove empty values then pick the last item.
If the item * 1 is the same as the item then we know it's a number.
(The return from explode is strings so we cant use is_int)

$url = "http://www.example.de/dashboard/2/";
$parts = array_filter(explode("/", $url));
$ending = end($parts);
if($ending*1 == $ending) echo $ending; //2
Andreas
  • 24,301
  • 5
  • 27
  • 57
1

First you need to target this url to script - in web server config. For nginx and index.php:

try_files $uri @rewrite_location;
location @rewrite_location {
        rewrite ^/(.*) /index.php?link=$1&$args last;
}

Second - you need to parse URI. In $end you find what you want

$link_as_array = array_values(array_diff(explode("/", $url), array('')));
$max = count($link_as_array) - 1;
$end = $link_as_array[$max];
Maksim
  • 106
  • 1
  • 10
0

I would think this way. If the URL is always the same, or the same format, I'll do the following:

  1. Check for the approx URL.
  2. Split the URL into pieces.
  3. Find if there's the part I am looking for.
  4. Extract the number.
<?php
  $url = "http://www.example.de/dashboard/2/";
  if (strpos($url, "www.example.de/dashboard") === 7 or strpos($url, "www.example.de/dashboard") === 8) {
    $urlParts = explode("/", $url);
    if (isset($urlParts[4]) && isNumeric($urlParts[4]))
      echo "Yes! It is {$urlParts[4]}.";
  }
?>

The strpos with 7 and 8 is for URL with http:// or https://.

The above will give you the output as the numeric part if it is set. I hope this works out.

Praveen Kumar Purushothaman
  • 154,660
  • 22
  • 177
  • 226