I am trying to use a router (AltoRouter) for the first time and am unable to call any page.
Web folder structure
The Code
Index.php
require 'lib/AltoRouter.php';
$router = new AltoRouter();
$router->setBasePath('/alto');
$router->map('GET|POST','/', 'home#index', 'home');
$router->map('GET|POST','/', 'display.php', 'display');
$router->map('GET','/plan/', 'plan.php', 'plan');
$router->map('GET','/users/', array('c' => 'UserController', 'a' => 'ListAction'));
$router->map('GET','/users/[i:id]', 'users#show', 'users_show');
$router->map('POST','/users/[i:id]/[delete|update:action]', 'usersController#doAction', 'users_do');
// match current request
$match = $router->match();
if( $match && is_callable( $match['target'] ) ) {
call_user_func_array( $match['target'], $match['params'] );
} else {
// no route was matched
header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}
I have a file named plan.php (display plan) in the plan folder and the hyperlink that I am trying is
Plan <?php echo $router->generate('plan'); ?>
which does not work.
Can you help?
You cannot call plan.php by passing plan.php as an argument to match function
Check examples at http://altorouter.com/usage/processing-requests.html
If you want to use content from plan.php
you should use map in the following format
$router->map('GET','/plan/', function() {
require __DIR__ . '/plan/plan.php';
} , 'plan');
to the file plan/plan.php add echo 'testing plan';
Also, double check that your .htaccess file contains
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]
Also, if you set base path with $router->setBasePath('/alto'); your index.php files should be placed in the alto directory so your url would be in that case http://example.com/alto/index.php
Working example:
require 'lib/AltoRouter.php';
$router = new AltoRouter();
$router->setBasePath('/alto');
$router->map('GET','/plan/', function( ) {
require __DIR__ . '/plan/plan.php';
} , 'plan');
// match current request
$match = $router->match();
if( $match && is_callable( $match['target'] ) ) {
call_user_func_array( $match['target'], $match['params'] );
} else {
// no route was matched
header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}
then this will work just fine
Plan <?php echo $router->generate('plan'); ?>
Related
I'm writing a small routing system for a project. It's not perfect and it's a custom solution that will map the url to their templates if requested from the user. I want to generate a dynamic page based on an unique id for each event inserted inside the database from the user. So if the user request the event 1234 it will get a page with the event detail at the url https://mysitedomain.com/event/1234. I need to understand how to achieve this with my code, I'm using a front controller and red bean as ORM to access the database.
Here is the code of my router. Any suggestion will be appreciated. for now I'm only able to serve the templates.
<?php
namespace Router;
define('TEMPLATE_PATH', dirname(__DIR__, 2).'/assets/templates/');
class Route {
private static $assets = ['bootstrap' => 'assets/css/bootstrap.min.css',
'jquery' => 'assets/js/jquery.min.js',
'bootstrapjs' => 'assets/js/bootstrap.min.js',
];
public static function init()
{
if( isset($_SERVER['REQUEST_URI']) ){
$requested_uri = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH);
if( $requested_uri === '/' ){
echo self::serveTemplate('index', self::$assets);
}
elseif( $requested_uri != '/' ){
$requested_uri = explode('/', $_SERVER['REQUEST_URI']);
if( $requested_uri[1] === 'event' ){
echo self::serveTemplate('event', self::$assets, ['event_id' => 001] );
}
else{
echo self::serveTemplate($view, self::$assets);
}
}
}
}
private static function serveTemplate(string $template, array $data, array $event_id = null)
{
if( !is_null($event_id) ){
$data[] = $event_id;
ob_start();
extract($data);
require_once TEMPLATE_PATH."$template.php";
return ob_get_clean();
}
else{
ob_start();
extract($data);
require_once TEMPLATE_PATH."$template.php";
return ob_get_clean();
}
}
}
?>
Writing a router from scratch is a little complex, you have to play a lots with regular expression to accommodate various scenario of requested url and your router should handle HTTP methods like POST, GET, DELETE, PUT and PATCH.
You may want to use existing libraries like Fast Route, easy to use and it's simplicity could give you idea how it is created.
I have been trying to get the index() method of the Home controller using the altorouter but am unable to. I have searched a few places but I could not find any help.
Here is the index.php
<?php
include 'system/startup.php';
include 'library/AltoRouter.php';
// Router
$router = new AltoRouter();
// Change here before upload
$router->setBasePath('/demo');
$router->map('GET|POST','/', 'home#index', 'home');
// match current request
$match = $router->match();
if( $match && is_callable( $match['target'] ) ) {
call_user_func_array( $match['target'], $match['params'] );
} else {
// no route matched
header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}
the home controller in the catalog>controller directory.
<?php
class home {
public function index() {
echo 'home';
}
}
Can anyone using or who ever used this altorouter guide?.
P.S. I have the autoload function in the startup.php file (included at the top of the index.php)
This is old thread but this can help you. You need match request in different way:
<?php
include 'system/startup.php';
include 'library/AltoRouter.php';
// Router
$router = new AltoRouter();
$router->setBasePath('/demo');
$router->map('GET|POST','/', 'home#index', 'home');
$match = $router->match();
if ($match === false) {
// here you can handle 404
} else {
list( $controller, $action ) = explode( '#', $match['target'] );
if ( is_callable(array($controller, $action)) ) {
call_user_func_array(array($controller,$action), array($match['params']));
} else {
// here your routes are wrong.
// Throw an exception in debug, send a 500 error in production
}
}
I am creating a custom Router for my web app.
I use MVC.
When I, for example, type fab.app/portfolio all is good.
But when I type fab.app/portfolio/ the css, images, and js are not displayed.
This is because the paths change. In the first case the path that it is looking for the images is fab.app/images/(the_image) but in the second case it is fab.app/portfolio/images/(the_image).
Also, in the index.php I have to have an entry for both the url with and without the slash in the end. Which I don't like. I would prefer to write it without the slash and it should work with the slash as well.
Below you can find the router and index.php
index.php
<?php
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../app/setup.php';
use Fab\Controllers;
use Fab\Router;
$router = new Router\Router();
$router->get('/', 'MainController', 'index');
$router->get('/portfolio', 'ItemsController', 'showAllItems');
$router->get('/portfolio/', 'ItemsController', 'showAllItems');
$router->get('/portfolio/[\w\d]+', 'ItemsController', 'single_item');
$router->get('/about', 'MainController', 'about');
$router->get('/contact', 'MainController', 'contact');
$router->get('/admin/dashboard', 'AdminController', 'index');
$router->get('/admin/dashboard/addItem', 'AdminController', 'addItem');
$router->get('/admin/dashboard/deleteItem', 'AdminController', 'deleteItem');
$router->get('/admin/dashboard/editItem', 'AdminController', 'editItem');
$router->get('/admin/dashboard/contactSupport', 'AdminController', 'contactSupport');
$router->post('/admin/addItem', 'AdminController', 'postAddItem');
$router->post('/admin/deleteItem', 'AdminController', 'postDeleteItem');
$router->post('/admin/editItem', 'AdminController', 'postEditItem');
//$router->get('/test', 'ItemsController', 'showAllItems');
////See inside $router
//echo "<pre>";
//print_r($router);
$router->submit();
Router.php
<?php
/**
* Created by PhpStorm.
* User: antony
* Date: 5/30/16
* Time: 3:31 PM
*/
namespace Fab\Router;
class Router
{
private $_getUri = array();
private $_getController = array();
private $_getMethod = array();
private $_postUri = array();
private $_postController = array();
private $_postMethod = array();
public function __construct()
{
}
/**
* Build a collection of internal GET URLs to look for
* #param $uri - The url that the user types in the browser
* #param $controller - The controller that will handle the url
* #param $method - The method of the controller that will run
*/
public function get($uri, $controller, $method)
{
$this->_getUri[] = $uri;
$this->_getController[] = $controller;
$this->_getMethod[] = $method;
}
/**
* Build a collection of internal POST URLs to look for
* #param $uri - The url that the user types in the browser
* #param $controller - The controller that will handle the url
* #param $method - The method of the controller that will run
*/
public function post($uri, $controller, $method)
{
$this->_postUri[] = $uri;
$this->_postController[] = $controller;
$this->_postMethod[] = $method;
}
public function submit()
{
$found = 0;
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); //get the url
//Map URL to page
foreach ($this->_getUri as $key => $value)
{
if ( $found = preg_match("#^$value$#", $path) )
{
// echo $key . ' => ' . $value; //See what the $path returns
//Find parameter if passed
$parts = explode('/', $path);
count($parts) > 2 ? $parameter=$parts[2] : $parameter=null;
//Instantiate Controller
$controller = 'Fab\Controllers\\' . $this->_getController[$key];
$controller = new $controller($parameter);
//Call the appropriate method
$method = $this->_getMethod[$key];
$controller->$method();
break;
}
}
//Show 404 page
if ( $found == 0 )
{
//Instantiate Controller
$controller = 'Fab\Controllers\MainController';
$controller = new $controller();
//Call the appropriate method
$method = 'error404';
$controller->$method();
die();
}
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); //get the url
foreach ($this->_postUri as $key => $value)
{
if ( $found = preg_match("#^$value$#", $path))
{
// echo $key . ' => ' . $value; //See what the $path returns
//Find parameter if passed
$parts = explode('/', $path);
count($parts) > 2 ? $parameter=$parts[2] : $parameter=null;
//Instantiate Controller
$controller = 'Fab\Controllers\\' . $this->_postController[$key];
$controller = new $controller($parameter);
//Call the appropriate method
$method = $this->_postMethod[$key];
$controller->$method();
break;
}
}
//Show 404 page
if ( $found == 0 )
{
//Instantiate Controller
$controller = 'Fab\Controllers\MainController';
$controller = new $controller();
//Call the appropriate method
$method = 'error404';
$controller->$method();
die();
}
}
}
}
.htaccess
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
AddType 'text/css; charset=UTF-8' css
</IfModule>
Example of calling css (but also images and js) in html
<link href="/css/my-admin-custom.css" rel="stylesheet">
-------------------------------------------------------------------
For sake of clarity, here is how I resolved the issue (per #Max13's answer).
This goes into Router.php:
/**
* If last char in URL is '/' redirect without it
* and also check if url is root '/' because this would result
* in infinite loop
*/
if ( ($path[strlen($path)-1] === '/') && !($path === '/') ) { //
$newPath = substr($path, 0, -1);
header("Location: $newPath", true, 302);
exit;
}
With and without trailing slash doesn't mean the same directory level, so I don't think it would be a good idea to "accept" both, in your router.
So, a good solution IMHO would be: During your checks, if the path ends with "/", then send a 302 Found header without the trailing slash.
-- Edit --
See (For header redirects and meta tag redirection, both are often used at the same time): https://www.arclab.com/en/websitelinkanalyzer/http-and-meta-redirects.html
i'm trying to use altorouter for set routing map of my php project, at this moment the file routes.php is this
<?php
$router = new AltoRouter();
$router->setBasePath('/home/b2bmomo/www/');
/* Setup the URL routing. This is production ready. */
// Main routes that non-customers see
$router->map('GET','/', '', 'home');
$router->map( 'GET', '/upload.php', 'uploadexcel');
$match = $router->match();
// call closure or throw 404 status
if( $match && is_callable( $match['target'] ) ) {
call_user_func_array( $match['target'], $match['params'] );
} else {
// no route was matched
header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}
?>
i have 2 files in the principal directory of my project, index.php and upload.php, what's wrong?
have you modified your .htaccess files to rewrite as per the altorouter site?
your routes look wrong. try like this:
// 1. protocol - 2. route uri -3. static filename -4. route name
$router->map('GET','/uploadexcel', 'upload.php', 'upload-route');
as it looks like you are wanting a static page (not a controller) try this (allows for both):
if($match) {
$target = $match["target"];
if(strpos($target, "#") !== false) { //-> class#method as set in routes above, eg 'myClass#myMethod' as third parameter in mapped route
list($controller, $action) = explode("#", $target);
$controller = new $controller;
$controller->$action($match["params"]);
} else {
if(is_callable($match["target"])) {
call_user_func_array($match["target"], $match["params"]); //call a function
}else{
require $_SERVER['DOCUMENT_ROOT'].$match["target"]; //for static page
}
}
} else {
require "static/404.html";
die();
}
which is pretty much from here: https://m.reddit.com/r/PHP/comments/3rzxic/basic_routing_in_php_with_altorouter/?ref=readnext_6
and get rid of that basepath line.
good luck
you car run class#function via "call_user_func_array":
if ($match) {
if (is_string($match['target']) && strpos($match['target'], '#') !== false) {
$match['target'] = explode('#', $match['target']);
}
if (is_callable($match['target'])) {
call_user_func_array($match['target'], $match['params']);
} else {
// no route was matched
header($_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
die('404 Not Found');
}
}
I am new to codeIgniter framework, When I uploaded codeigniter website on linux server on a sub domain It gives the error "Unable to load the requested file: Home\home.php" but working fine on my local windows machine, I have checked the case sensitivity issue but those all are fine, also I have checked the .htaccess file but no success. any suggestion.
here is my controller "home.php":
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->template->set('nav', 'home');
$this->load->model('Home_model', 'home');
}
public function index()
{
$this->template->set('title', 'Books Bazaar : Home');
$this->template->load('template', 'Home\home');
}
?>
and my .htaccess file contains :
DirectoryIndex index.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php/$1 [L,QSA]
domain where I have uploaded the site is :
http://books.atntechnologies.com/
Thanks
this is how codeigniter checks your file
function load($tpl_view, $body_view = null, $data = null)
{
if ( ! is_null( $body_view ) )
{
if ( file_exists( APPPATH.'views/'.$tpl_view.'/'.$body_view ) )
{
$body_view_path = $tpl_view.'/'.$body_view;
}
else if ( file_exists( APPPATH.'views/'.$tpl_view.'/'.$body_view.'.php' ) )
{
$body_view_path = $tpl_view.'/'.$body_view.'.php';
}
else if ( file_exists( APPPATH.'views/'.$body_view ) )
{
$body_view_path = $body_view;
}
else if ( file_exists( APPPATH.'views/'.$body_view.'.php' ) )
{
$body_view_path = $body_view.'.php';
}
else
{
show_error('Unable to load the requested file: ' . $tpl_name.'/'.$view_name.'.php');
}
$body = $this->ci->load->view($body_view_path, $data, TRUE);
if ( is_null($data) )
{
$data = array('body' => $body);
}
else if ( is_array($data) )
{
$data['body'] = $body;
}
else if ( is_object($data) )
{
$data->body = $body;
}
}
$this->ci->load->view('templates/'.$tpl_view, $data);
}
so you need '/' instead of '\' for $this->template->load('template', 'Home\home');