4

I was recently surprised to learn that PHP will automagically and unpreventably turn all periods to underscores in the names of POST fields, because periods are not allowed in variable names in PHP.

I have POST data that is keyed with names that have arbitrary data in them, and I was thinking about Base64 encoding the POST names to avoid the period problem. However, the Base64 alphabet includes the characters +, / and =. These letters are also not allowed in variable names, but are these alright for POST names? What will PHP do with them?

uk4321
  • 1,028
  • 8
  • 18
  • 1
    I wouldn't be surprised if they got converted too, but try it out. Do a `print_r($_POST);` to see the result – Pekka Dec 30 '13 at 01:43
  • Personally i think PHP needs to have a setting telling it to stop doing that. It's basically a leftover from the days of register_globals, but 5.4 actually removes register_globals (and more importantly, you've been able to have dots in variable names for a while now -- just not directly. `${'a.b'} = 42;` works fine in 5.2, and probably before that. – cHao Dec 30 '13 at 01:44
  • @cHao I do too, that's a very magical and annoying behavior. I didn't know you could do `${}` to use an almost-arbitrary string as a variable, I guess that's a good indication that `/` and `=` and stuff are OK in variable names. – uk4321 Dec 30 '13 at 02:11

2 Answers2

4

The following characters not allowed in variable names:

chr(32) ( ) (space)
chr(46) (.) (dot)
chr(91) ([) (open square bracket)
chr(128) - chr(159) (various)

(Cite: Get PHP to stop replacing '.' characters in $_GET or $_POST arrays?)

For the other guys, +, /, and = are fine for $_POST, and for variable names.

First, if you are sure all the underscores in $_POST should be periods (which may or may not be a fair assumption, but...)

<form name=test>
<input type=text name="+./=" value='hello'>
<input type=submit>

<?php
foreach ($_POST as $key=>$postVar)
{
$newKey=str_replace("_",".",$key);
$newPost[$newKey]=$postVar;
}
$_POST=$newPost;
echo $_POST['+./=']; //hello

and in variable names, you can use Variable variables

${'var+./='}=1;
echo ++${'var+./='}; //2
?>
Community
  • 1
  • 1
chiliNUT
  • 18,989
  • 14
  • 66
  • 106
2

From their website:

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus:

'^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*' 

which includes a correction a user made in the comments on that same page.

Starts with a letter [a-z], or underscore, or anything between \x7f to \xff.

This can be followed by anything listed above as well as digits.

Without testing, and with errors turned off, my assumption is that PHP will replace any character that shouldn't be there with an underscore. Hope that helps.

Duniyadnd
  • 4,013
  • 1
  • 22
  • 29