Getting $_GET variable when using mod_rewrite - php

I am having issues getting $_GET variables with mod_rewrite enabled. I have the following .htaccess:
RewriteEngine On
RewriteRule ^/?Resource/(.*)$ /$1 [L]
RewriteRule ^$ /home [redirect]
RewriteRule ^([a-zA-Z]+)/?([a-zA-Z0-9/]*)$ /app.php?page=$1&query=$2 [L]
and app.php is:
<?php
require("controller.php");
$app = new Controller();
and controller.php is:
<?php
require("model.php");
require("router.php");
class Controller{
//--------Variables------------
private $model;
private $router;
//--------Functions------------
//Constructor
function __construct(){
//initialize private variables
$this->model = new Model();
$this->router = new Router();
$page = $_GET['page'];
//Handle Page Load
$endpoint = $this->router->lookup($page);
if($endpoint === false) {
header("HTTP/1.0 404 Not Found");
}else {
$this->$endpoint($queryParams);
}
}
private function redirect($url){
header("Location: /" . $url);
}
//--- Framework Functions
private function loadView($view){
require("views/" . $view . ".php");
}
private function loadPage($view){
$this->loadView("header");
$this->loadView($view);
$this->loadView("footer");
}
//--- Page Functions
private function indexPage(){
$this->loadPage("home");
}
private function controlPanel(){
echo "Query was " . $code;
/*
if($this->model->set_token($code)){
$user = $this->model->instagram->getUser();
}else{
echo "There was an error generating the Instagram API settings.";
}
*/
$this->loadPage("controlpanel");
}
private function autoLike(){
$this->loadPage("autolike");
}
private function about(){
$this->loadPage("about");
}
}
So an example of a URL that I might have is /app.php?page=controlpanel&query=null which would be rewritten as /controlpanel. The problem I have is that I have another page which sends a form to /controlpanel resulting in a URL like /controlpanel?code=somecode.
What I am trying to do is get $_GET['code'] and I cannot seem to do this. Can anyone help? Apologies in advance for a bit of a code dump.

Change
RewriteRule ^([a-zA-Z]+)/?([a-zA-Z0-9/]*)$ /app.php?page=$1&query=$2 [L]
to
RewriteRule ^([a-zA-Z]+)/?([a-zA-Z0-9/]*)$ /app.php?page=$1&query=$2 [L,QSA]
QSA is to append the query string
From the docs
"When the replacement URI contains a query string, the default behavior of RewriteRule is to discard the existing query string, and replace it with the newly generated one. Using the [QSA] flag causes the query strings to be combined."

Related

routing in MVC doesn't work in server, but work properly in localhost

i made a simple mvc with routing system. When i deployed it in 000webhost to be tested, all links don't work. They only shown in the URL. No error message.
i tried to change php version on the server to be the same as my php on localhost, it still didn't work
I guess maybe there's something wrong in my htaccess
here is the routing code:
<?php
class App
{
// controller, method, dan parameter
protected $controller = 'Home',
$method = 'index',
$params = [];
public function __construct()
{
$url = $this->parseURL();
// get controller dari url
if (file_exists('app/controllers/' . $url[0] . '.php')) {
$this->controller = $url[0];
// unset untuk menentukan param
unset($url[0]);
}
// call controller
require_once 'app/controllers/' . $this->controller . '.php';
// instansiasi class controller
$this->controller = new $this->controller;
// get method from url
// check if method exist in url
if (isset($url[1])) {
// cek ketersediaan method pada controller
if (method_exists($this->controller, $url[1])) {
$this->method = $url[1];
// unset untuk menentukan param
unset($url[1]);
}
}
// get param from url
// check array
if (!empty($url)) {
$this->params = array_values($url);
}
// run controller and method and param if exist
call_user_func_array([$this->controller, $this->method], $this->params);
}
public function parseURL()
{
if (isset($_GET['url'])) {
$url = rtrim($_GET['url'], '/');
$url = filter_var($url, FILTER_SANITIZE_URL);
$url = explode('/', $url);
return $url;
}
}
}
and here's the htaccess
Options -Multiviews
DirectoryIndex index.php
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [L]
RewriteRule !^(public/|index\.php) [NC,F]

Error 403, access denied on infinityfree domain hosting

I'm currently testing my project which has MVC integrated in it upon deploying in a free hosting site i've encountered an error 403 this error didn't appear since the development stage. My current knowledge why this error occurs is maybe the type of directives i've used in my htaccess? or something maybe in the core itself any toughts or suggestions to this particular problem :)
domain/
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ public/ [L]
RewriteRule (.*) public/$1 [L]
</IfModule>
domain/public
<IfModule mod_rewrite.c>
Options -Multiviews
RewriteEngine On
RewriteBase /domain/public
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
</IfModule>
domain/app
Options -Indexes
domain/app/libraries/Core.php
<?php
class Core {
protected $currentController = 'Pages';
protected $currentMethod = 'index';
protected $params = [];
public function __construct(){
//print_r($this->getUrl());
$url = $this->getUrl();
// Look in BLL for first value\
if($url != NULL){
if(file_exists('../app/controllers/' . ucwords($url[0]). '.php')){
// If exists, set as controller
$this->currentController = ucwords($url[0]);
// Unset 0 Index
unset($url[0]);
}
}
// Require the controller
require_once '../app/controllers/'. $this->currentController . '.php';
// Instantiate controller class
$this->currentController = new $this->currentController;
// Check for second part of url
if(isset($url[1])){
// Check to see if method exists in controller
if(method_exists($this->currentController, $url[1])){
$this->currentMethod = $url[1];
// Unset 1 index
unset($url[1]);
}
}
// Get params
$this->params = $url ? array_values($url) : [];
// Call a callback with array of params
call_user_func_array([$this->currentController, $this->currentMethod], $this->params);
}
public function getUrl(){
if(isset($_GET['url'])){
$url = rtrim($_GET['url'], '/');
$url = filter_var($url, FILTER_SANITIZE_URL);
$url = explode('/', $url);
return $url;
}
}
}

Changing default Access to a function in a php file under the subdirectory in .htaccess

I want to run my activeIndex() function in GuestsController.php file under a subdirectory as the first default page when the user enters the url.
For this reason, I have written such a script in my .htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/controllers/GuestsController.php/.*
RewriteRule ^/mvc/(.*) /controllers/GuestsController.php?method=$actionList?page=$1 [QSA,L]
And my GuestsController.php file is:
<?php
class GuestsController
{
public function actionIndex()
{
echo "start";
sleep(1);
include(dirname(__FILE__) . '/../views/guests/index.php' );
}
public function actionList()
{
$guests = Guests::findAll();
echo json_encode( $guests );
}
}
I still could not manage to achieve my goal.
How I should modify .htaccess file to run actionIndex() function directly?
Thanks,

How do I get clean URLS for only 2 variables?

I've seen/read questions about clean URLs with .htaccess, but for the life of me, I cannot get them to work for my specific needs. I keep getting 404 message.
Example: www.mysite.com/article.php?id=1&title=my-blog-title
I would like for url to be: www.mysite.com/article/1/my-blog-title
Here's what I have so far in my .htaccess:
Options -MultiViews
#DirectorySlash on
RewriteCond %{HTTP_HOST} !^www [NC]
RewriteRule .* http://www.%{HTTP_HOST}%{REQUEST_URI} [L]
# Rewrite for article.php?id=1&title=Title-Goes-Here
RewriteRule ^article/([0-9]+)/([0-9a-zA-Z_-]+) article.php?id=$1&title=$2 [NC,L]
#Rewrite for certain files with .php extension
RewriteRule ^contact$ contact.php
RewriteRule ^blogs$ blogs.php
RewriteRule ^privacy-policy$ privacy-policy.php
RewriteRule ^terms-of-service$ terms-of-service.php
Also, is this how I would link to article? article.php?id=<?php echo $row_rsBlogs['id']; ?>&slug=<?php echo $row_rsBlogs['slug']; ?> or article/<?php echo $row_rsBlogs['id']; ?>/<?php echo $row_rsBlogs['slug']; ?>
I'm using Dreamweaver, but I am comfortable hand coding.
Thanks in advance.
You could use a dispatcher by telling the webserver to redirect all request to e.g. index.php..
In there a dispatch instance analizes the request and invokes certain controllers (e.g. articlesControllers)
class Dispatcher
{
// dispatch request to the appropriate controllers/method
public static function dispatch()
{
$url = explode('/', trim($_SERVER['REQUEST_URI'], '/'), 4);
/*
* If we are using apache module 'mod_rewrite' - shifting that 'request_uri'-array would be a bad idea :3
*/
//array_shift($url);
// get controllers name
$controller = !empty($url[0]) ? $url[0] . 'Controller' : 'indexController';
// get method name of controllers
$method = !empty($url[1]) ? $url[1] : 'index';
// get argument passed in to the method
$parameters = array();
if (!empty($url[2])) {
$arguments = explode('/', $url[2]);
foreach ($arguments as $argument) {
$keyValue = explode('=',$argument);
$parameters[$keyValue[0]] = $keyValue[1];
}
}
// create controllers instance and call the specified method
$cont = new $controller;
if(!method_exists($cont,$method)) {
throw new MethodNotFoundException("requested method \"". $method . "\" not found in controller \"" . $controller . "\"");
}
$cont->$method($parameters);
}
}
in .htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ index.php

Themes outside application

I read this post and I want to use similar solution, but with db.
In my site controller after():
$theme = $page->get_theme_name(); //Orange
Kohana::set_module_path('themes', Kohana::get_module_path('themes').'/'.$theme);
$this->template = View::factory('layout')
I checked with firebug:
fire::log(Kohana::get_module_path('themes')); // D:\tools\xampp\htdocs\kohana\themes/Orange
I am sure that path exists. I have directly in 'Orange' folder 'views' folder with layout.php file.
But I am getting: The requested view layout could not be found
Extended Kohana_Core is just:
public static function get_module_path($module_key) {
return self::$_modules[$module_key];
}
public static function set_module_path($module_key, $path) {
self::$_modules[$module_key] = $path;
}
Could anybody help me with solving that issue?
Maybe it is a .htaccess problem:
# Turn on URL rewriting
RewriteEngine On
# Put your installation directory here:
# If your URL is www.example.com/kohana/, use /kohana/
# If your URL is www.example.com/, use /
RewriteBase /kohana/
# Protect application and system files from being viewed
RewriteCond $1 ^(application|system|modules)
# Rewrite to index.php/access_denied/URL
RewriteRule ^(.*)$ / [PT,L]
RewriteRule ^(media) - [PT,L]
RewriteRule ^(themes) - [PT,L]
# Allow these directories and files to be displayed directly:
# - index.php (DO NOT FORGET THIS!)
# - robots.txt
# - favicon.ico
# - Any file inside of the images/, js/, or css/ directories
RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|static)
# No rewriting
RewriteRule ^(.*)$ - [PT,L]
# Rewrite all other URLs to index.php/URL
RewriteRule ^(.*)$ index.php/$1 [PT,L]
Could somebody help?
What I am doing wrong?
Regards
[EDIT]
My controller code:
class Controller_Site extends Controller_Fly {
public static $meta_names = array('keywords', 'descriptions', 'author');
public function action_main() {
$this->m('page')->get_main_page();
}
public function action_page($page_title) {
$this->m('page')->get_by_link($page_title);
}
public function after() {
$page = $this->m('page');
$metas = '';
foreach(self::$meta_names as $meta) {
if (! empty($page->$meta)) {
$metas .= html::meta($page->$meta, $meta).PHP_EOL;
}
}
$theme = $page->get_theme_name();
Kohana::set_module_path('themes', Kohana::get_module_path('themes').'/'.$theme);
$menus = $page->get_menus();
$this->template = View::factory('layout')
->set('theme', $theme)
->set('metas', $metas)
->set('menus', $menus['content'])
->set('sections', $page->get_sections())
->set_global('page', $page);
if ($page->header_on) {
$settings = $this->m('setting');
$this->template->header = View::factory('/header')
->set('title', $settings->title)
->set('subtitle', $settings->subtitle)
->set('menus', $menus['header']);
}
if ($page->sidebar_on) {
$this->template->sidebar = View::factory('sidebar', array('menus' => $menus['sidebar']));
}
if ($page->footer_on) {
$this->template->footer = View::factory('footer');
}
parent::after();
}
}
and parent controller:
abstract class Controller_Fly extends Controller_Template {
protected function m($model_name, $id = NULL) {
if (! isset($this->$model_name)) {
$this->$model_name = ORM::factory($model_name, $id);
}
return $this->$model_name;
}
protected function mf($model_name, $id = NULL) {
return ORM::factory($model_name, $id);
}
}
[Edit 2]
Previous link to post was dead, link was:
http://forum.kohanaframework.org/comments.php?DiscussionID=5744&page=1#Item_0
My guess is that your controller has a __construct() method and you aren't calling parent::__construct
Actually, I think for kohana V3 __construct needs to also be passed the $request object as follows:
public function __construct(Request $request)
{
parent::__construct($request);
}
I realized that I need to init all modules once again:
$theme = $page->get_theme_name();
Kohana::set_module_path('themes', Kohana::get_module_path('themes').'/'.$theme);
Kohana::modules(Kohana::get_modules());
Now I don't have an error. Instead I am getting white screen of death:
$this->template is null
:(
[EDIT]
Now I know, I had:
$this->template = View::factory('layout')
->set('theme', $theme)
->set('metas', $metas)
->set('menus', $menus['content'])
->set('sections', $page->get_sections())
->set_gobal('page', $page);
Ofcourse I forgot that set_global doesn't return $this :D
Anyway everything working now :)
I have one more question about efficiency. I am calling Kohana::modules() second time in request flow. Is this a big deal according to efficiency?
Regards

Categories