Git Product home page Git Product logo

main's Introduction

PHP ROUTER

Secure router with XSS and CSRF

  1. Download the file ".htaccess" and place it under the root directory (html, htdocs, or www) of your web server

  2. Download the file "router.php" and place it under the root directory (html, htdocs, or www) of your web server

  3. Download the file "routes.php" and place it under the root directory (html, htdocs, or www) of your web server

In the browser go to "localhost" or "127.0.0.1" and you should see the word "Index" displayed in the website.

Feel free to delete all the routes in the "routes.php" file and create your own. Most likely you want to keep the last route for "Page not found".

For details about routing, visit https://phprouter.com

main's People

Contributors

phprouter avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

main's Issues

.htaccess ignores woff files

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]

Awesome router

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.

Using phprouter for project in subdirectory

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.

Not working in Nginx

Unfortunately not working in Nginx. Only a blank white page appears. Why can it be caused? No problem with rewrites.

Pagination in phprouter App

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

Problems with curl and certificates.

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?

MAMP not working?

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!

How to use dynamic routes.

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?

How do I add absolute paths?

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?

Can't get the variable from the url, and only routes if the .php file is in the root directory

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?

Page isn't working

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.
image

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]`

render index and 404 always in the end

Hello!

First of all, thank you for the work of this library, my question is the following, my index is empty, and it always redirects me to page 404, if I have it with content, it loads the content and all the way down it loads 404, it will be a problem my local server? use MAMP

Captura de pantalla 2023-09-20 a la(s) 12 06 53 p m

Working in cpanel, not in my PC[ubuntu]

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

phprouter works with subfolder in XAMMP but not in LAMP!

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?

optional params

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.

More documentation

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.

$_SESSION doesn't work

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.

Problems with callbacks functions

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.

UTM tags and other option or unknown parameters

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

How can I route all requests to my single-page application?

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]

Global variables doesnt work

Hi, i dont know what happend but when i use routing, i cant use global variables. If i dump $GLOBALS, they doesnt show

Not redirecting to dashboard.

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

post method not working

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]

Callback issue

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.

php mvc controller

How to write the controller?

get( '/index' , 'views/indexcontroller@index' );

phprouter does not work inside subfolders.

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?

Callback on dynamic route

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
});

Files downloading from page driven by PHP router.

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

How to force HTTPS?

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?

group

Can you create a function to make a groupt of routers?

like

profile/show
profile/get
profile/edit
...
.
.

Redundant Code

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.

HTACCESS Error

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

Callback function is not working for Root "/" route

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

AJAX calls

If I use the documented route format in Ajax calls, will the redirection shown in your htaccess file still happen?

Problem with src and href

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?

Global variables not working

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.

How to pass query parameters to the path_to_include

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.

Keeps redirecting to 404 page

Hi,
Just tried using your code AS IT IS on my XAMPP (MacOS). When I try to go to any file (even a simple index.php under views/ folder), it redirects to 404 page. Any suggestions here?
image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.