0

How do I remove .php and replace ? with / at the same time.

I have

http://localhost/testingproject/testing.php?mode=getdata

I want it to be called from the browser like this:

http://localhost/testingproject/testing/getdata

In replacing ? data, I want it to be compatible with dir.

Like in dir, I have:

testing.php
user.php
dashboard.php

So, if the user calls http://localhost/testingproject/user, alone, there is no need to parse ? to / as user is a valid PHP file: user.php.

But if user the calls http://localhost/testingproject/user/abc, then user.php page should get $_GET['mode'] value abc.

I've searched but still cannot find compatible htaccess code.

MrWhite
  • 43,179
  • 8
  • 60
  • 84
  • 4
    It might be a better idea to do the routing from inside the main file (index.php usually), and use .htaccess to only to send all requests to that main file (instead of the 404 page, what it does by default). – Shomz Nov 28 '21 at 16:18
  • 1
    What have you tried so far? Where are you stuck? – Nico Haase Nov 28 '21 at 16:19
  • Does something like https://stackoverflow.com/questions/4026021/remove-php-extension-with-htaccess help? – Nico Haase Nov 28 '21 at 16:19
  • 3
    Yes, for your use-case, a PHP router sounds like the best option. You can go [simple](https://www.taniarascia.com/the-simplest-php-router/) or more [complex](https://github.com/nikic/FastRoute) – Chris Haas Nov 28 '21 at 16:22
  • for now, i can remove .php but cannot get method so, i can now call test?mode=abc instead of test.php?mode=abc which i need to be test/abc so currently, my main problem is getting ?mode= as / – user8355629 Nov 28 '21 at 16:31
  • 1
    Where are you placing your `.htaccess` file? – MrWhite Nov 28 '21 at 16:43
  • xampp/htdocs/testproject/backend/ dir of backend. .htaccess test.php user.php .... – user8355629 Nov 28 '21 at 17:12

1 Answers1

0

I found one that works. Now, i can call http://localhost/testproject/backend/user/abc instead of http://localhost/testproject/backend.php?mode=abc In Replace GET variables with slashes .htaccess

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^([^/]+)/?$ $1.php [L]

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^([^/]+)/([^/]+)/?$ $1.php?mode=$2 [L,QSA]

  • Hello :) you could try this [link](https://www.buzzphp.com/posts/replace-query-string-in-url-using-htaccess) – 0xe1λ7r Nov 29 '21 at 04:03