Adam Ramadhan
Adam Ramadhan

Reputation: 22820

get a controller and method from url?

ok i have a url from $_SERVER['REQUEST_URI']

lets say it give us a url

http://localhost/controller/method

i have tried something like

explode('/',$_SERVER['REQUEST_URI'])

and it gave us like

array
  0 => string '' (length=0)
  1 => string 'controller' (length=10)
  2 => string 'method' (length=6)

what is the best way to get the controller or method ? or removeing the 0 in the array ? ( first array ) ?

so it will be like

$controller = 'controller';
$method = 'method';

from above inputs. maybe about list ? still no clue using list().

edit heres what ive done so far

    $this->url = str_replace(config('foldertoscript'), NULL, $_SERVER['REQUEST_URI']);
    $hello = explode('/',$this->url);var_dump($hello);
    array_shift($hello);
    list($controller,$method) = $hello;
    var_dump($hello,$controller);

in a class

Thanks for looking in.

Adam Ramadhan

Upvotes: 0

Views: 3131

Answers (3)

Catalin Marin
Catalin Marin

Reputation: 1242

For the same matter I use url_rewriting.

I have a rule that says ^([a-zA-Z0-0-_\/.]+)$ index.php?url=$1 (this is not a copy paste from my code, but you get the idea) then if you say $_URL = $_REQUEST["url"];

$directive = explode("/",$_URL);

you will get what you need, as for the parameters you could say module/method/id/1/data/2

you have to take care of your parameters and it works if you use the GET method for

navigation only(as it should be used). Also makes the stuff much safer as no one can send SQL

injections via get or any "smart" directives.

Upvotes: 0

Gatman
Gatman

Reputation: 594

Use array_shift to remove the first array item.

http://php.net/manual/en/function.array-shift.php

Example:

$your_array = array_shift($your_array);
$controller = $your_array[0];
$method = $your_array[1];

Upvotes: 0

Or Weinberger
Or Weinberger

Reputation: 7482

To remove the first element of an array, you can use array_shift().

$_SERVER['REQUEST_URI'] gives you the url without the "http://www.yoursite.com".

You can use something like this

<?php
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}

echo curPageURL();
?>

Hope this helps.

Upvotes: 0

Related Questions