Don't let autoglobals=0 get you down

Submitted on: 1/1/2015 1:58:00 PM
By: (from psc cd)  
Level: Beginner
User Rating: By 4 Users
Compatibility: PHP 3.0, PHP 4.0
Views: 3318
     A good thing to do is to never rely on autoglobals. They might just be turned off. For those not familiar with how autoglobals work, if you call a page say test.php?foo=bar, autoglobals allow you to access foo by using $foo, rather than using $_GET['foo']. However, if autoglobals are off, $foo will give a warning, and it's value will be empty rather than 'bar'. This little piece of code mimics autoglobals, thus preventing you from having to rewrite entire applications because they relied on autoglobals. Note that as of PHP 4.2, autoglobals are off by default.

				As PHP documentation specifies, you should not rely on autoglobals, so if you are a clean programmer, you probably don't need this code.

However, those off you who decided to go for the time gain offered by autoglobals might just need this.

The code makes use of variable variables, a feature not that many languages posses. We just loop throug each variable in $_GET and $_POST, and assign it to the correspondending $variable.

while(list($key,$value)= each($_POST)) {
	$tmp = $key;
	$$tmp = $value;		
while(list($key,$value)= each($_GET)) {
	$tmp = $key;
	$$tmp = $value;		
if (isset($test)) {
	echo "Test is set: $test";
} else {
	echo "Test not set";

In order to test this example, ENABLE autoglobals on your server. Point to the page, and set the test variable (http://yourserver/test.php?test=123). You will see that the page will say that $test is set.
Now DISABLE autoglobals. Reload the page, and you'll see that $test is still set. Finally, comment away the two while loops and reload the page. You will now see that $test isn't set.

The best use of this is to paste the code into a seperate file, and include the file at the beginning of the page that requires its functionallity.

Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)

Other User Comments

 There are no comments on this submission.

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)

To post feedback, first please login.