Search code examples
phpcontent-management-systemurl-routing

Retrieve parameter from URL php


I'm having this PHP MVC Application that I'm trying to implement. My attempt here is to add/edit/delete CATEGORIES. A category has a name and a description. It's view is basically a table with categories data and a link for edit/delete.

I've loaded dynamically and finished the add Category part, but I'm stuck at edit/delete.

My routing is set up like this: Controller/Action/Parameter.

Click EDIT link, application grabs the ID of the row and proceeds to edit page, so : /categories/edit/(categoryID)
So if I wish to edit the first entry entry, it'll go to categories/edit/1

My question is: how to I retrieve the category ID? That 1 from the URL.


$_GET['id'] does not work as my routing doesn't look like categories/edit.php?id=etc

EDIT

<?php
$routes = explode('/', $_SERVER['REQUEST_URI']);

// get controller name
if (isset($routes[1]) && !empty($routes[1])) {
    $controllerName = $routes[1];
}

// get name action
if (isset($routes[2]) && !empty($routes[2])) {
    $actionName = $routes[2];
}

if (isset($routes[3]) && !empty($routes[3])) {
    $param = $routes[3];
} 

Apologies. Here's the route.php. Also, using array_pop to grab the id does not appear to work.


Solution

  • You could simply use something like this,

        // Get the current URL
        $url = $_SERVER['REQUEST_URI'];
    
        // Explode with /
        $parts = explode('/', rtrim($url, '/'));
    
        // Pop the element in the end of the array
        $id = array_pop($parts);