Marco
Marco

Reputation: 2737

Rewriterule with optional parameter

this is my .htaccess file

..
RewriteRule ^songbook(?:/([a-z]))?/?$ music/songbook.php?char=$1 [L]

with that rule i can use the following url's:

http://www.example.com/songbook
http://www.example.com/songbook/

http://www.example.com/songbook/a
http://www.example.com/songbook/a/

So far so good. The problem occurs when i try the get the char in PHP, like so:

if (isset($_GET['char'])) {
   echo 'FOUND a char';

} else {
   echo 'there is NO char';
}

For some reason, it always finds a char, even when there is no char provided. My rewrite rule says that the char is optional, but i guess i'm doing something wrong.

How do i write the rewriterule so that the char is optional so the if condition in PHP works?

Thanks

Upvotes: 0

Views: 141

Answers (2)

Croises
Croises

Reputation: 18671

You can change the .htaccess:

RewriteRule ^songbook/?$ music/songbook.php [L]
RewriteRule ^songbook/([a-z])/?$ music/songbook.php?char=$1 [L]

Upvotes: 1

undone
undone

Reputation: 7888

Problem is that your rewrite rule always defines char in query string even if it's an empty string. You have two options :

1- Edit your php:

if (isset($_GET['char'])  &&  !empty($_GET['char'])) {
   echo 'FOUND a char';
} else {
   echo 'there is NO char';
}

2- Edit your .htaccess:

Upvotes: 1

Related Questions