abhishek02
abhishek02

Reputation: 3

How to fetch id from url?

I want to fetch id from the url.

URL:- localhost/projects/PortalGrocery/development/admin/projects/home/edit/27

I have tried:-

    $update_url = $_SERVER['REQUEST_URI'];
    $path = parse_url($update_url, PHP_URL_PATH);
    $pathComponents = explode("/", trim($path, "/"));
    $ID = $pathComponents[7];

It is working fine but when i upload my project on live site, i have to change the component number everytime and in every controller as there is difference in no. of components.

So, I want to know if there is any other method to fetch to do so..?

Upvotes: 0

Views: 217

Answers (4)

Vishal Purohit
Vishal Purohit

Reputation: 261

I think instead of all this

$update_url = $_SERVER['REQUEST_URI'];
$path = parse_url($update_url, PHP_URL_PATH);
$pathComponents = explode("/", trim($path, "/"));
$ID = $pathComponents[7];

You should try the following trick

$ID = substr(strrchr($_SERVER['REQUEST_URI'], '/'), 1);

Upvotes: 2

Abhishek Saha
Abhishek Saha

Reputation: 2564

you can do it the below way..

$update_url = "localhost/projects/PortalGrocery/development/admin/projects/home/edit/27";
$path = parse_url($update_url, PHP_URL_PATH);
$pathComponents = explode("/", trim($path, "/"));

echo $pathComponents[sizeof($pathComponents) - 1]; //gives 27

Upvotes: 0

Kapil Sharma
Kapil Sharma

Reputation: 10417

Since your id always come at the end, Zerkms solution will work

$id = substr(strrchr($_SERVER['REQUEST_URI'], '/'), 1);

Upvotes: 0

zerkms
zerkms

Reputation: 254926

$id = substr(strrchr($_SERVER['REQUEST_URI'], '/'), 1);

This code extracts the part of the string after the last /

Upvotes: 4

Related Questions