Passing a variable with href via PHP.

Technical Q&A involving operating systems, networking, software, and hardware issues.

Moderator: jasonb

Post Reply
User avatar
jasonb
Site Administrator
Posts: 105
Joined: Tue Apr 22, 2003 1:54 pm
Location: Toronto, Canada
Contact:

Passing a variable with href via PHP.

Post by jasonb »

Right - I've just finished pulling out all of my hair figuring this one out. (Or I would have if I had any hair to start with...)

Take the following PHP snippet:

Code: Select all

if ($id) {
do something 
} else {
printf("<a href=\"%s?id=1\">click</a>", $PHP_SELF);
}
This is a very simplified example. However, it should demonstrate the problem. Something like this would be used if you want to display different things depending on what you've clicked on.

With PHP 4.2.0 and above, the variable "register_globals" is off by default for security reasons. There is a massive amount of discussion over this but, essentially, there are good reasons for doing this. The "downside" of this, however, is that the above code won't work. The URL will not set the session variable to "1". I refused to change the setting to "on" because I didn't want to just bypass the issue, but determine how to do things properly.

After over an hour and a half (!) of trying to come up with a simple solution to the problem, I finally stumbled on an answer. Notice the additional line of code at the beginning:

Code: Select all

$id = $_GET["id"];
if ($id) {
do something 
} else {
printf("<a href=\"%s?id=1\">click</a>", $PHP_SELF);
}
That's it. Since the URL method uses "GET" all you need to do is set the session variable to the result of the last URL used (which would have happened automatically if register_globals were set to "on"). If it's the first time you've gone to the page, it will remain null and nothing will happen.
Post Reply