MVC reads controller URL and actions

I wrote my own mvc for php and it seems to work fine for me. But I am having problems getting the controller and action:

http://www.example.com/controller/action

this works fine, but as soon as small changes in the url appear, my code breaks the application. eg:

http://www.example.com/controller ? thi breaks, saying that controller?does not exist,

http://www.example.com/controller/action ? thi breaks, saying that action?does not exist,

I can’t understand why it takes ?there, and if any body knows more reliable, in order to get the right controller and action that I would like to know.

here is my code:

the entire request is redirected to the same index.php page using .htaccess

class Framework {

   ....

   private function setup() {
     $uri = (isset($_SERVER['REQUEST_URI']))?$_SERVER['REQUEST_URI']: false;
     $query = (isset($_SERVER['QUERY_STRING']))?$_SERVER['QUERY_STRING']: '';
     $url = str_replace($query,'',$uri);
     $arr = explode('/',$url);
     array_shift($arr);
     $this->controller =!empty($arr[0])?$arr[0]:'home';
     $this->action = isset($arr[1]) && !empty($arr[1])?$arr[1]:'index';
   }
}
0
source share
2 answers

$ _ SERVER ['QUERY_STRING'] does not include ?, so when you execute $url = str_replace($query,'',$uri);, you are not replacing ?. So he is looking for a controller namedcontroller?

There are several ways in this section:

  • replace '?'.$query
  • Use explode('?', $url)to separate query string from URI
  • Get $_SERVER['REQUEST_URL'](which doesn't include the query string), and not get everything, and then split yourself

Personally, I would go with the latter option, because wherever the code is already written for you, it tends to be faster and more reliable than anything you can write.

+2
source

You must fix the problem using /before?

+1

All Articles