amok khan
amok khan

Reputation: 29

Get id from url in a variable PHP

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']; 
    }

Upvotes: 0

Views: 13117

Answers (5)

Mulan
Mulan

Reputation: 135425

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 ...

Upvotes: 3

NID
NID

Reputation: 3294

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];

Upvotes: 1

Twinfriends
Twinfriends

Reputation: 1997

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];

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167250

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];

Upvotes: 4

Shailesh Singh
Shailesh Singh

Reputation: 421

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

Upvotes: 8

Related Questions