0

Have a problem to get the id from the URL in a variable!

The Url is like this domain.com/article/1123/

and its like dynamic with many id's

I want to save the 1123 in a variable please help!

a tried it with this

    if(isset($_GET['id']) && !preg_match('/[0-9]{4}[a-zA-Z]{0,2}/', $_GET['id'], $id)) { 
        require_once('404.php'); 
    } else { 
        $id = $_GET['id']; 
    }
amok khan
  • 29
  • 1
  • 1
  • 6
  • What was the problem? What did you make to not get it? – Praveen Kumar Purushothaman Dec 21 '16 at 12:54
  • Are you using a framework? If so which one – RiggsFolly Dec 21 '16 at 12:54
  • Possible duplicate of [Very simple regex to get the numbers in url: http://artige.no/bilde/6908](http://stackoverflow.com/questions/7807692/very-simple-regex-to-get-the-numbers-in-url-http-artige-no-bilde-6908) – Alive to die - Anant Dec 21 '16 at 12:54
  • @Anant You don't need a Regex for this dude. – Praveen Kumar Purushothaman Dec 21 '16 at 12:55
  • You want to read and learn about request rewriting and search friendly URLs. – arkascha Dec 21 '16 at 12:56
  • 2
    If an answer solved your problem, consider accepting the answer. Here's how http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work then return here and do the same with the tick/checkmark till it turns green. This informs the community, a solution was found. Otherwise, others may think the question is still open and may want to post (more) answers. You'll earn points and others will be encouraged to help you. *Welcome to Stack!* – Jay Blanchard Dec 21 '16 at 13:06

5 Answers5

8

The absolute simplest way to accomplish this, is with basename()

echo basename('domain.com/article/1123');

Which will print

1123

the reference url click hear

Community
  • 1
  • 1
Shailesh Singh
  • 421
  • 2
  • 8
4

I would do in this way:

  1. Explode the string using /.
  2. Get the length of the exploded array.
  3. Get the last element, which will be the ID.

Code

$url = $_SERVER[REQUEST_URI];
$url = explode("/", $url);
$id = $url[count($url) - 1];
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
3

You should definitely be using parse_url to select the correct portion of the URL – just in case a ?query or #fragment exists on the URL

$parts = explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

$parts[0]; // 'domain.com'
$parts[1]; // 'article'
$parts[2]; // '1123'

You'll probably want to reference these as names too. You can do that elegantly with array_combine

$params = array_combine(['domain', 'resource', 'id'], $parts);

$params['domain'];   // 'domain.com'
$params['resource']; // 'article'
$params['id'];       // '1123'

I'm really feeling like a procrastinator right now so I made you a little router. You don't have to bother dissecting this too much right now; first learn how to just use it, then you can pick it apart later.

function makeRouter ($routes, callable $else) {
  return function ($url) use ($routes, $else) {
    foreach ($routes as $route => $handler) {
      if (preg_match(makeRouteMatcher($route), $url, $values)) {
        call_user_func_array($handler, array_slice($values, 1));
        return;
      }
    }
    call_user_func($else, $url);
  };
}

function makeRouteMatcher ($route) {
  return sprintf('#^%s$#', preg_replace('#:([^/]+)#', '([^/]+)', $route));
}

function route404 ($url) {
  echo "No matching route: $url";
}

OK, so here we'll define our routes and what's supposed to happen on each route

// create a router instance with your route patterns and handlers
$router = makeRouter([

  '/:domain/:resource/:id' => function ($domain, $resource, $id) {
    echo "domain:$domain, resource:$resource, id:$id", PHP_EOL;
  },

  '/public/:filename' => function ($filename) {
    echo "serving up file: $filename", PHP_EOL;
  },

  '/' => function () {
    echo "root url!", PHP_EOL;
  }
], 'route404');

Now let's see it do our bidding ...

$router('/domain.com/article/1123');
// domain:domain.com, resource:article, id:1123

$router('/public/cats.jpg');
// serving up file: cats.jpg

$router('/');
// root url!

$router('what?');
// No matching route: what?

Yeah, I was really that bored with my current work task ...

Mulan
  • 129,518
  • 31
  • 228
  • 259
1

That can be done quite simple. First of all, you should create a variable with a string that contains your URL. That can be done with the $_SERVER array. This contains information about your server, also the URL you're actually at.

Second point is to split the URL. This can be done by different ways, I like to use the p_reg function to split it. In your case, you want to split after every / because this way you'll have an array with every single "directory" of your URL.

After that, its simply choosing the right position in the array.

$path = $_SERVER['REQUEST_URI']; // /article/1123/
$folders = preg_split('/', $path); // splits folders in array
$your_id = $folders[1];
Twinfriends
  • 1,972
  • 1
  • 14
  • 34
1

To be thorough, you'll want to start with parse_url().

$parts=parse_url("domain.com/article/1123/");

That will give you an array with a handful of keys. The one you are looking for is path.

Split the path on / and take the last one.

$path_parts=explode('/', $parts['path']);

Your ID is now in $path_parts[count($path_parts)-1];

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
NID
  • 3,238
  • 1
  • 17
  • 28