9.9. Handling Remote Variables with Periods in Their Names

Problem

You want to process a variable with a period in its name, but when a form is submitted, you can’t find the variable.

Solution

Replace the period in the variable’s name with an underscore. For example, if you have a form input element named foo.bar, you access it inside PHP as the variable $_REQUEST['foo_bar'].

Discussion

Because PHP uses the period as a string concatenation operator, a form variable called animal.height is automatically converted to animal_height, which avoids creating an ambiguity for the parser. While $_REQUEST['animal.height'] lacks these ambiguities, for legacy and consistency reasons, this happens regardless of your register_globals settings.

You usually deal with automatic variable name conversion when you process an image used to submit a form. For instance: you have a street map showing the location of your stores, and you want people to click on one for additional information. Here’s an example:

<input type="image" name="locations" src="locations.gif">

When a user clicks on the image, the x and y coordinates are submitted as locations.x and locations.y. So, in PHP, to find where a user clicked, you need to check $_REQUEST['locations_x'] and $_REQUEST['locations_y'].

It’s possible, through a series of manipulations, to create a variable inside PHP with a period:

${"a.b"} = 123; // forced coercion using {} $var = "c.d"; // indirect variable naming $$var = 456; print ${"a.b"} . "\n"; print $$var ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.