Variables in friendly URLs [duplicate]

1

How are you?

I'm doing the user profile and there are 3 tabs, that is, three areas by which users can browse. For the profile, I rewrote the following in .htaccess:

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

This is not the problem, the problem is that I want to pass GET variables in the normal way too, as in the tabs example, getting something awesome URL:

profile/245/user-name?tab=about

But it does not read the variable when I put it to test:

echo $_GET['tab'];

Returns the following error:

Notice: Undefined index: tab in C:...\profile.php on line 14

NOTE: In the pages I rewrite that DO NOT have VARIABLE, it reads normally! I could even include this variable in the .htaccess that way, but suppose you have several of these for little things, type? Edit = 1 ...

    
asked by anonymous 17.07.2016 / 20:30

1 answer

2

The problem is that you are completely discarding the query string in your rewrite.

One way is to capture what comes after ? and include in redirect, something like this:

RewriteRule ^profile/([0-9]+)/([a-z0-9-]+)/?\??(.*)?$ profile.php?id=$1&name=$2&$3
                                        grupo 3 ^                adicionado aqui ^

I'm basically giving you an initial sense of logic, you need to take other factors into consideration (for example, someone might pass id or name and your application would get confused if you're not ready for it)

See working in RegExr . (I used a backslash to escape normal bars.)

A better way is this, posted on a linked question:

RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?caminho=$1&%{QUERY_STRING} [NC,L]

So you get the whole path in $_GET['caminho'] and can split with a simple explode, managing as many levels as necessary.


Now, a personal comment. This thing of converting such a "friendly URL" into GET parameters, I find it horrible (but it's just like almost everyone does). Some applications made by "smart" people simply take the direct path of the URL, with explode or something, avoiding all those problems. I would suggest thinking about this alternative once you have mastered this part of redirection.

The most amazing thing is that I've seen people teaching this GET simulation in certain college courses, but since it's the same people who teach PHP to use PHP only with OOP and MVC, / sub>

    
17.07.2016 / 21:39