phprouter / main Goto Github PK
View Code? Open in Web Editor NEWSecure router with XSS and CSRF
License: MIT License
Secure router with XSS and CSRF
License: MIT License
I tried to customize the folder structure but I got this "Page isn't working" error.
Here's my folder structures, htaccess, and index code file.
index.php
<?php // include router php file require_once 'routes/routes.php';
.htaccess
`RewriteEngine On
RewriteCond %{REQUEST_URI} !(.png|.jpg|.gif|.jpeg|.zip|.css|.svg|.js)$
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php/$1 [L]`
Unfortunately not working in Nginx. Only a blank white page appears. Why can it be caused? No problem with rewrites.
I see someone else opened an issue about this, but I am also having issues with global variables.
I am also having issues with global variables. Can you show code as an example that it works @phprouter ?
Code:
$testVar = "testing";
function globVar() {
global $testVar;
echo $testVar;
}
globVar();
Output of var_dump($GLOBALS['testVar']);
:
NULL
The above code works absolutely fine if I am not using the router.
When trying to make curl requests in a php script it cant seem to find keys and certs, have narrowed it down to the router being the problem and cant seem to find a fix for it. Do you guys now any way around this?
Hi, I'm using XAMPP on Windows and ONLY have a .htaccess and an index.php file in the htdocs folder.
ALL OTHER php files including routes.php and router.php are in a folder outside htdocs named src.
The website works just fine when on XAMPP BUT NOT IN LAMP. Here is the content of the files:
Files in htdocs:
index.php
<?php
require_once("../src/routes.php");
?>
.htaccess
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
RewriteCond %{REQUEST_URI} !(\.png|\.jpg|\.gif|\.jpeg|\.css|\.svg|\.js)$
RewriteRule (.*) index.php [QSA,L]
Files outside htdocs:
routes.php
<?php
require_once("../src/router.php");
get('/', '../src/home.php');
get('/register', '../src/register.php');
get('/signup', '../src/register.php');
get('/login', '../src/login.php');
any('/any','../src/any.php');
router.php
<?php
session_name('session');
session_start();
function get($route, $path_to_include){
if( $_SERVER['REQUEST_METHOD'] == 'GET' ){ route($route, $path_to_include); }
}
function post($route, $path_to_include){
if( $_SERVER['REQUEST_METHOD'] == 'POST' ){ route($route, $path_to_include); }
}
function put($route, $path_to_include){
if( $_SERVER['REQUEST_METHOD'] == 'PUT' ){ route($route, $path_to_include); }
}
function patch($route, $path_to_include){
if( $_SERVER['REQUEST_METHOD'] == 'PATCH' ){ route($route, $path_to_include); }
}
function delete($route, $path_to_include){
if( $_SERVER['REQUEST_METHOD'] == 'DELETE' ){ route($route, $path_to_include); }
}
function any($route, $path_to_include){ route($route, $path_to_include); }
function route($route, $path_to_include){
$ROOT = $_SERVER['DOCUMENT_ROOT'];
if($route == "/any"){
include_once("$ROOT/$path_to_include");
exit();
}
$request_url = filter_var($_SERVER['REQUEST_URI'], FILTER_SANITIZE_URL);
$request_url = rtrim($request_url, '/');
$request_url = strtok($request_url, '?');
$route_parts = explode('/', $route);
$request_url_parts = explode('/', $request_url);
array_shift($route_parts);
array_shift($request_url_parts);
if( $route_parts[0] == '' && count($request_url_parts) == 0 ){
include_once("$ROOT/$path_to_include");
exit();
}
if( count($route_parts) != count($request_url_parts) ){ return; }
$parameters = [];
for( $__i__ = 0; $__i__ < count($route_parts); $__i__++ ){
$route_part = $route_parts[$__i__];
if( preg_match("/^[$]/", $route_part) ){
$route_part = ltrim($route_part, '$');
array_push($parameters, $request_url_parts[$__i__]);
$$route_part=$request_url_parts[$__i__];
}
else if( $route_parts[$__i__] != $request_url_parts[$__i__] ){
return;
}
}
// Callback function
if( is_callable($path_to_include) ){
call_user_func($path_to_include);
exit();
}
include_once("$ROOT/$path_to_include");
exit();
}
function out($text){echo htmlspecialchars($text);}
function set_csrf(){
if( ! isset($_SESSION["csrf"]) ){ $_SESSION["csrf"] = bin2hex(random_bytes(50)); }
echo '<input type="hidden" name="csrf" value="'.$_SESSION["csrf"].'">';
}
function is_csrf_valid(){
if( ! isset($_SESSION['csrf']) || ! isset($_POST['csrf'])){ return false; }
if( $_SESSION['csrf'] != $_POST['csrf']){ return false; }
return true;
}
When I use the same code in LAMP on Ubuntu, only the localhost/ returns a 200 response (the homepage ../src/home.php is loaded corectly) and ALL OTHER PAGES return a 404 Not Found page. Any ideas how to make this work on LAMP?
This was a very good library and it was all I wanted, but except that I can use it only if my project is hosted at the root folder of the server.
But I have multiple projects there and I want to use this one inside localhost/example-project folder.
That is not working since you're using DOCUMENT_ROOT everywhere, any fix?
Can't get it work with subdomain. Error 500
Google re captcha not working ,proper redirection not happening in live server , in local host it's working fine.
If I use the documented route format in Ajax calls, will the redirection shown in your htaccess file still happen?
I uploaded my entire files on my server and it appears to have some htaccess issues. It displays HTTP Error 500. When I tried to rename the htaccess, it works just fine. Can you help?
Thanks,
Leo
When I try to use callback function for "/" route it's not working instead it's showing some errors
Here is the error
Fatal error: Uncaught Error: Object of class Closure could not be converted to string in D:\Projects\Client\routes\router.php:54 Stack trace: #0 D:\Projects\Client\routes\router.php(8): route('/', Object(Closure)) #1 D:\Projects\Client\routes\web.php(10): get('/', Object(Closure)) #2 {main} thrown in D:\Projects\Client\routes\router.php on line 54
The first quarter of the code is redundant and does the exact same thing regardless of the function you call. (Lines 3-18). Line 20 is a variable for nothing.
I'm using ubuntu and ran a local server in cmd php -S localhost:4000
. This was not working.
Then I directly deployed this on my hosting which works fine. No changes in code, just the same one here.
Working in hosting, not in my local machine. Would like to know if there are any config needed to be done to be able to run on php -S localhost
Is there any way to modify the route function to allow using an unknown number of parameters in a callback? perhaps be able to detect *
in the route and map the remaining parameters using a variadic ?
get('/search/$table/*', function ($area, ...$rest) {
echo "Search area: $area<br>";
echo "Search rest: ";
print_r($rest); // e.g. "age=25/name=martyn/type=intj/dnd=lg"
}
would match
/search/entries/year/2005/month/may
/search/users/firstname/josh
/search/stats/age=25/name=martyn/type=intj/dnd=lg
would not match
/search/games
I realise using a querystring is an alternative, e.g. /search/stats?age=25&name=martyn&type=intj&dnd=lg
but it's not as url/seo friendly.
I am loading fonts from my assets but i noticed that they were not being loaded.
Then realized that the .htaccess
has the following line
RewriteCond %{REQUEST_URI} !(\.png|\.jpg|\.webp|\.gif|\.jpeg|\.zip|\.css|\.svg|\.js)$
which is very limited in terms of files.
My proposed solution is below.
I also added some commets for how to use redirections as I happened to need them in my project!
🍻
RewriteEngine On
# You can also user redirections
# Using RewriteBase is particularly useful to avoid typing the folder name in each RewriteRule
# RewriteBase /folder/
# Make sure you don't add a / before new/path for the RewriteBase to take effect
# RewriteRule ^/?path/?$ new/path [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) routes.php [QSA,L]
How to write the controller?
get( '/index' , 'views/indexcontroller@index' );
Hi! Trying to get this to work on MAMP / Mac Os. Unfortunately I only get the 404 page displayed, no matter which route I use. Also "/" to the index page does not work. What am I doing wrong? Cheers!
Please has anyone using this Library - phprouter, been able to successfully implement a Search Result Pagination?
Please, if you have, kindly share it with me. I just am not able to get it to work ! Or, am I trying the impossible? Is this Router not designed to handle Paginations?
Urgent help will be highly appreciated.
Adolf
Hello, currently it only works if you put it in the htdocs folder, is there any way to work in subfolders?
How do I add absolute paths so that I can identify the images and files inside the public folder, where they contain the CSS, JS and img?
When creating a function callback with the link below it throws an error
get('/', function() {
echo "test";
});
However, if you change the link to literally anything else, it will work. This issue seems to only be present on /
link.
The error message created is attached below.
Fatal error: Uncaught Error: Object of class Closure could not be converted to string in C:\xampp\htdocs\rbc\router.php:38 Stack trace: #0 C:\xampp\htdocs\rbc\router.php(6): route('/', Object(Closure)) #1 C:\xampp\htdocs\rbc\routes.php(14): get('/', Object(Closure)) #2 {main} thrown in C:\xampp\htdocs\rbc\router.php on line 38
This issue was tested with a brand new clone of this repo.
This is a great library, exactly what I need for my project.
With that out of the way... Documentation is needed.
The examples are great but they are just examples and not every one is experienced on programming.
Thank you for this contribution it has helped me a lot.
In local host site was working fine but on cpannel , after clicking on login button , session gets set but I am still on login page not moving to homepage .I have to manually browse to home page then I am able to go to homepage.
It's same issue with all the post() routs
Hi
I have a REST API written in PHP and a single-page application written in Elm.
How can I make all requests starting with /api/*
go to their corresponding script in the backend and let everything else go to the frontend (WITH the url preserved)?
I tried this, but it didn't work.
get('/api/foo', 'api/foo.php');
get('/api/bar', 'api/bar.php');
get('/*', 'website/index.html');
I can access the API properly at /api/*
, and the index page at /
.
However, any other URL will return a blank page, whereas it should return the index page and the single-page application would take care of rendering the corresponding content or a 404 page.
Ps.:
Here's my .htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule (.*) routes.php [QSA,L]
Our platform will use UTM tags for analytics on some occasions and in others we may have other optional paramters for example of a register page, we may provide an early access code with /register?eac=123
but /register
should still work. How can we handle these scenarios? Thank you
Al momento de añadir un archivo css o script en el archivo php, lo bloque y no deja acceder al archivo local del proyecto, me puedes ayudar?
When adding a css or script file in the php file, it blocks it and does not allow access to the local project file, can you help me?
This router is very fast and simple to understand. However, it would be better to remove session_start and have it invoked only when called by the set_csrf function. Not everyone prefers to set cookies on their page, especially when some pages are cached.
oai?verb=ListIdentifiers&metadataPrefix=oai_dc
not working
The Router is great though but something is off, can anybody tell me how ajax works in it?
How do I retrieve the value in the file?.
Example
STANDARD-URL: item.php?size=10
In the file php, I can print them like this.
DYNAMIC-URL: get('/item/size/$size', 'views/item.php');
¿How can I see the value now?
¿Cómo recupero el valor en el archivo?
Ejemplo
URL ESTÁNDAR: item.php?size=10
En el archivo php, puedo imprimirlos así.
URL DINÁMICA: get('/item/size/$size', 'views/item.php');
¿Cómo puedo ver el valor ahora?
I'm trying to use PHP Router in my app, and the problem is when I call the .pdf file to download.
Here is an example code
<a href=„media/pdfs/file.pdf">FILE</a>
The router goes to the 404 page.
Could you advise any solution?
Thanks
post('/login', 'controllers/LoginController.php');
when i submit form i see this any('/404','views/404.php');
.htacces file:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_METHOD} ^(POST)
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
Hey guys, this looks like a cool router, but I have a problem with query strings. I would like to use something like this?
https://url.com/id/1?status=1&color=blue&size=1,2,3&merchant=99,15,28,37,45,69
Any idea how to make this work?
Can you create a function to make a groupt of routers?
like
profile/show
profile/get
profile/edit
...
.
.
Hi,
If I have a project in
example.com/new_project
and I want to do routing (e.g.)
example.com/new_project/user/name => example.com/new_project/user.php?name=name
Do I need to change the code? I can't seem to get it working, all I get is blank html when I do the static routing.
Hi, I have included router.php and routes.php in a "src" folder outside htdocs and I have included only index.php in my htdocs folder.
In the index.php file I have the following code:
require_once("../src/routes.php");
Everything seems to work right (secure connection) when I type https://localhost, but not when I type http://localhost or localhost. Here is my .htaccess file:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
RewriteCond %{REQUEST_URI} !(\.png|\.jpg|\.gif|\.jpeg|\.zip|\.css|\.svg|\.js)$
RewriteRule (.*) index.php [QSA,L]
Any tips on what might be the problem?
diff --git a/router.php b/router.php
index 1ff3ccd..73221f1 100644
--- a/router.php
+++ b/router.php
@@ -1,7 +1,10 @@
Callbacks don't pass the parameters in a dynamic route. Don't know if this is a bug or an unimplemented feature, either way it is an issue.
Take the snippet below (crudely written, apologize for any syntax errors)
get('/user/$user' function($id) {
// your code here n stuff
});
I have the same folder structure as this guy in this video: (https://www.youtube.com/watch?v=T9To0blu9qs), but it's not working me like in the video. If I write localhost/test/items in the url it won't work. But if I change the get('/items', 'views/items.php') to get('/items', 'items.php') it will work.
My other problem is, when I have the get('/product/$type/', 'product.php'), in the product.php I cannot get the $type variable, because it does not exist. Any idea why this is happening?
Hello,
I started using the callback functions (which are an awesome add) but I have a problem with it.
Even when using different urls, only the first one is always used (also if I try to go to /admin, it redirect to /)
If I comment the login header redirection, there is just no redirections at all (even on logout and session_unset()
is not ran)
get('/', 'app/index/index.php');
get('/user/login', function(){
$_SESSION['logged'] = true;
header('Location: /');
});
get('/user/logout', function(){
session_unset();
header('Location: /');
});
get('/admin', 'app/admin/index.php');
Any idea why this happen?
EDIT : I added the test callback (the same one as website show) before the login callback and when I go to /user/logout
, it just show Awesome
.
Im having problems in putting my code with routing in a sub folder of wamp, www/urls
does any one have the same problem? I add $ROOT = $_SERVER['DOCUMENT_ROOT']."/urls"; and it loads the index but i try to access -> href="product/shoes/color/blue">Products</a and the url just increments the params like http://localhost/urls/product/shoes/color/product/shoes/color/blue and so on..
Hi,
Your router causes infinite loop in cloudflare.
Setting up just bare-bones script in cloudflare (HTTP not HTTPS server and HTTPS redirect disabled on cloudflare), it causes infinite redirect loop.
Hy,
I’m using phprouter to routing my website. Recently, I face an issue that sessions doesn’t keep between pages and between different php fils, such as between header and footer. Does this problem have been already found and how do you know how to fix it ?
Thank you.
Really like this library which will save me a lot of work.
The docs seem to discourage the use of query parameters but it's not uncommon for APIs to have query parameters as allowed by the OpenAPI spec. However it looks like they aren't made available to the path_to_include, meaning $_GET is empty.
I can easily edit the code to parse the query parameters into a $_GET array but wanted to check I'm not missing something before doing that.
Hi, i dont know what happend but when i use routing, i cant use global variables. If i dump $GLOBALS, they doesnt show
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.