开发者

How do I get PHP to ignore unescaped ampersands in query string (e.g. ?name=M&M's doesn't become array('name' => 'M', 'M\'s' => ''))

开发者 https://www.devze.com 2023-01-29 16:14 出处:网络
With a URL like: http://any.php?name=M&M\'s PHP\'s $_GET variable is array(\'name\' => \'M\', \'M\\s\' => \'\').

With a URL like: http://any.php?name=M&M's

PHP's $_GET variable is array('name' => 'M', 'M\s' => '').

Is there a way to get PHP to ignore that un-escaped ampersand?

------ Earlier question (that lead to one above) ------

Hi guys,

With a mod_rewrite rule like this...

RewriteRule ^wiki/([A-Za-z0-9_,+&'\-\)\(]+)$ php/data.php?name=$1 [L,NC]

And a link like this (in plain text, that's M&M's)...

http://any.com/wiki/M开发者_如何学JAVA%26M%27s

I'm getting this from data.php...

<?php echo 'Name:'. $_GET['name']; ?>

Name: M

What happened to the rest of the name?

Thanks!


I don't know if this helps, but are you sure you need the backslashes in the range expression? Normally you don't need to escape parentheses there (they would never be legal), and you don't escape the hyphen either: you include it either in first or last position. So your line would be:

RewriteRule ^wiki/([-A-Za-z0-9_,+&')(]+)$ php/data.php?name=$1 [L,NC]

And, again, I don't know mod_rewrite, so I'm just taking two stabs in the dark here but:

  1. Is the $ just before "php" part of the regex, or some sort of variable reference? Is there confusion?
  2. Are you sure this rule should be operating on the de-escaped version of the URL? If it's being passed a string with %'s in it, then your regex should have %'s in it...no?


So I did a little more testing, and it looks like PHP's fault!

First of all, it appears mod_rewrite decodes any characters before running through the re-write rules. If I remove the "$" and "'" from my regex's character class (or add the "%" as Steve suggested), I get a 404 error. Thus, my RewriteRule's syntax and mod_rewrite looks better and better (especially after cleaning it up like Steve suggested).

If I dump the page's $_GET variable, I see:

<?php var_dump($_GET); ?>
array(2) { ["name"]=> string(8) "Almond_M" ["M\'s"]=> string(0) "" } 

Ha! It's a PHP problem! So now the question is, how do I get PHP to ignore the unescaped ampersand (and I'd like to keep it un-escaped so it looks pretty for users).

0

精彩评论

暂无评论...
验证码 换一张
取 消