I am trying to create a php project. At the time of routing the url routing works perfect with virtualhost domain. But the functionality doesn't work properly when I placed my project inside a subfolder. My Router Class looks like
class Router{
private $request;
public function __construct($request){
$this->request = $request;
}
public function get($route, $file){
$uri = trim( $this->request, "/" );
$uri = explode("/", $uri);
if (empty($uri[0])) {
$file['platform'] = '';
$file['controller'] = 'Index';
$file['action'] = 'index';
}
if($uri[0] == trim($route, "/")){
define("PLATFORM", isset($file['platform']) ? $file['platform'] : '');
define("CONTROLLER", isset($file['controller']) ? $file['controller'] : 'Index');
define("ACTION", isset($file['action']) ? $file['action'] : 'index');
$plarform = !empty(PLATFORM)? PLATFORM . DS: '';
define("CURRENT_CONTROLLER", CONTROLLER_PATH . $plarform);
define("CURRENT_VIEW", VIEW_PATH . PLATFORM . DS);
}
}
}
And initialize the function like
require CORE_PATH.'Router.php';
$request = $_SERVER['REQUEST_URI'];
$router = new Router($request);
But the same work in
http://www.mysite.local
, http://www.mysite.local/about
, http://www.mysite.local/contact
which is a virtualhost.
But When I call something like
http://localhost/mysite/
, http://localhost/mysite/about
, http://localhost/mysite/contact
it doesn't work as I expect. Please suggest me any idea to working on this.
My .htaccess
as like below.
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
I have already tried with
RewriteBase /mysite
Ya Finally I got a solution after working on it.
I just changed $_SERVER['REQUEST_URI'];
to $SERVER['PHP_SELF'];
.
There is an index.php
in the $SERVER['PHP_SELF'];
.
That is if URL is http://www.mysite.local/about
actual PHP_SELF
is
http://www.mysite.local/index.php/about
Same as in
http://localhost/mysite/index.php/about
So I Just explode the siteurl with index.php
as below.
require CORE_PATH.'Router.php';
$request = $_SERVER['PHP_SELF'];
$requesturi = explode('index.php', $request);
unset($requesturi[0]);
$request = implode($requesturi);
$router = new Router($request);