1

I want to use mod_rewrite with PHP, parse the URL with this format:

http://www.domain.com/Path-to-index.php/Class_to_Load/Function_to_Execute/Arguments_as_array_to_the_function

The class to load will be included of the directory classes, with a strtolower then ucfirst, like:

http://www.domain.com/Path-to-index.php/SAMPLE will include classes/Sample.php and execute the function action_index, because no function was used.

Then, when this url is open: http://www.domain.com/Path-to-index.php/SAMPLE/Login/User, PHP should include classes/Sample.php and execute action_Login($args = Array(0 => "User"));.

Please I need to know how to do that.

1 Answers1

2

Your index.php could look something like this:

// @todo: check if $_SERVER['PATH_INFO'] is set
$parts = explode('/', trim($_SERVER['PATH_INFO'], '/')); // get the part between `index.php` and `?`

// build class name & method name
// @todo: implement default values
$classname = ucfirst(strtolower(array_shift($parts)));
$methodname = "action_" . array_shift($parts);

// include controller class
// @todo: secure against LFI
include "classes/$classname.php"

// create a new controller
$controller = new $classname();

// call the action
// @todo: make sure enough parameters are given by using reflection or default values
call_user_func_array(Array($controller, $methodname), $parts);

Your .htaccess for removing index.php from the url:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

It's always interesting to roll your own framework to learn more about PHP, but if you are really coding something bigger, I highly recommend using a well-known and well-documented framework. There are a lot of good frameworks out there, which are well-tested and used in production before. Just take a look at all the @todo notices above. These are all issues, which are already handled by a framework and you don't need to care about these things.

MarcDefiant
  • 6,649
  • 6
  • 29
  • 49
  • Almost everything is working properly, the class is included, but I got this error: Warning: call_user_func_array() expects exactly 2 parameters, 3 given in /srv/www/index.php on line 19 – user2018198 Jan 28 '13 at 13:59
  • I totally forgot if you want to call a method using user_call_func_array you need to pass an array containing the object and the method name as first parameter – MarcDefiant Jan 28 '13 at 14:03
  • Fixed with: call_user_func_array(Array($controller, $methodname), $parts); Thanks! – user2018198 Jan 28 '13 at 14:12