RewriteRule with htaccess for custom PHP project

Viewed 177

I'm trying to learn RewriteRule for htaccess on a small project. It's my first time writing codes for htaccess. So here's how the so-called project looks like (simplified):

root folder ___________ /admin/edit_order.php
                 |_____ /users/edit_order.php
                 |_____ index.php
                 |_____ sample.php

So, for this part I have used the following codes on my .htaccess file:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [NC]

So, what I've learned so far is that the 2nd and 3rd lines are like if conditions and they consider if the path entered by user/used by the script is not a folder, and is a file. In such case it removes the .php extension and shows only the name.

So I have something like abc.com/sample. It also works for sub-folders (I have abc.com/admin/edit_order) So far so good.

But I have a problem with query strings or when I want to pass variables using the URL. Sometimes I may need to pass 1 variable, and sometimes 2 variables. So this is the code I wrote:

RewriteRule ^sample/([0-9]+) sample.php?id=$1 [NC]
RewriteRule ^sample/([0-9]+)/([0-9a-zA-Z_-]+) sample.php?id=$1&name=$2 [NC]

I wrote the first line for when I only need to pass an ID, and the second line where I might also need to pass a name. This also is the codes on sample.php and other PHP files (edit_order.php on both admin and users folders):

<?php
    $id=$_GET['id'];
    $name=$_GET['name'];
?>
<html>
    <body>
        id: <?php echo $id; ?>
        <br>
        name: <?php echo $name; ?>
    </body
</html>

Now, the thing is when I pass only 1 variable (ID) it works just fine (what I enter is abc.com/user/(any number)). The script shows:

id: any_given_number
name: (prints nothing)

But even when I pass 2 variables, it shows the same result (what I enter is abc.com/user/(any number)/(any name)).

For the sub-folder, I added this piece of code:

RewriteRule ^admin/edit_order/([0-9]+) admin/edit_order.php?id=$1 [NC]
RewriteRule ^admin/edit_order/([0-9]+)/([0-9a-zA-Z_-]+) admin/edit_order.php?id=$1&name=$2 [NC]

It also has the same outcome.

What I basically want, is to show only file names without their extensions either on root folder or sub-folders, and query strings without their default looks (something like abc.com/sample/23/John). Also it would be perfect if I can write a code where I can use custom names for files, for instance, instead of abc.com/admin/edit_order/34/Bag I can get abc.com/admin/EditOrder/34/Bag.

I really appreciate some help on fixing this code.

0 Answers
Related