Pedro Ivo
Pedro Ivo

Reputation: 39

Problem with .htaccess accessing variable in method in PHP with forward slash

I'm having a problem accessing a variable.

My method is requested this way:

http://example.com/method/parameter

I have a specific .htaccess file that manages that:

<ifmodule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/]+)/?$ index.php?categoryId=$1 [QSA,L] 
</ifmodule>

This enables the $categoryId variable to be passed by a forward slash.

Here is the deal, I'm trying to pass another variable adding another forward slash. The complete request would be something like this:

http://example.com/method/parameter/orderby

I've tried changing the .htaccess file to:

<ifmodule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/]+)/?$ index.php?categoryId=$1?orderBy=$2 [QSA,L] 
</ifmodule>

There was no change. Am I missing something?

Upvotes: 0

Views: 103

Answers (1)

lovelace
lovelace

Reputation: 1215

What you need to do to capture multiple query string parameters in the $_GET array in index.php is change your RewriteRule to the following:

RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ index.php?method=$1&param=$2&orderby=$3 [L,QSA]

I've used method, param and orderby as you indicated in the question.

Just repeat the pattern ([^/]+)/ for each query string parameter you want to add, and reference them respectively with $1, $2, $3 etc.

Note: in your original RewriteRule you did not format the query string properly, you need to use & between the parameters, not ?(the question mark is used as a separator, and is not part of the query string.).

The above solution requires three parameters, if however you wanted to make the parameters optional, you can use ? in the pattern, as follows:

RewriteRule ^([^/]+)?/?([^/]+)?/?([^/]+)?/?$ index.php?categoryId=$1&orderBy=$2&something=$3 [L,QSA]

A question mark makes a preceding token in the regular expression optional.

Upvotes: 2

Related Questions