I'm probably being a little thick, but I can't seem to find an answer to this one. I'm moving from a server with register globals ON to one with it being off. It's a good thing, but unfortunately I have been used to years and years working with register globals being ON which has resulted in me writing sloppy code. I am now trying to fix that.
I'm trying to rewrite some old code which has variable variables within $_POST.
I know this is a silly example, but it illustrates the problem I am trying to solve. The following would work with register globals ON:
<?php $variable = "fullname";?>
<form action="/test/" method="post">
<label for="fullname">Full Name:</label> <input name="fullname" type="text" value="<?php echo $$variable;?>" size="20" maxlength="150" />
<input name="submit" type="submit" value="Go!" />
</form>
How do I make this work with register globals off? The following obviously doesn't work:
<?php $variable = "fullname";?>
<form action="/test/" method="post">
<label for="fullname">Full Name:</label> <input name="fullname" type="text" value="<?php echo $_POST[$$variable];?>" size="20" maxlength="150" />
<input name="submit" type="submit" value="Go!" />
</form>
Please go easy on me- I know I am probably being stupid, but I can't seem to get my head round this.
Simple, just $_POST[$variable]
. (Or $_GET
or maybe $_REQUEST
, as appropriate.)
However note that when you output text to HTML, you must encode it, or you will be vulnerable to cross-site-scripting attacks:
<input type="text"
name="<?php echo htmlspecialchars($variable);?>"
value="<?php echo htmlspecialchars($_POST[$variable]);?>"
size="20" maxlength="150"
/>
(I typically define a function called h
that does echo htmlspecialchars
, to cut down on this excessive amount of typing.)