5.11. Using $_ENV and $_SERVERBefore you get control in your script, PHP sets several variables for you containing information about the server, the environment, and your visitor's request. These are stored in the superglobal arrays $_ENV and $_SERVER, but their availability depends on whether the script is being run through a web server or on the command line. The most commonly used $_SERVER variables are shown in Table 5-3. Note: of these, only PHP_SELF is available on the command line.
Of those, HTTP_REFERER and HTTP_USER_AGENT are the most important, as you can use these two to find out a lot about your visitor and then take the appropriate action. For example: <?php if (isset($_SERVER['HTTP_REFERER'])) { print "The page you were on previously was {$_SERVER['HTTP_ REFERER']}<br />"; } else { print "You didn't click any links to get here<br />"; } ?> <a href="refer.php">Click me!</a> If you load that page in your browser by typing the URL in by hand, the "You didn't click any links to get here" text is shown because HTTP_REFERER has not been set. However, if once the page is loaded you follow the "Click me!" link, the page will reload itself; this time, HTTP_REFERER will be set and the other message should appear. Although it can be easily spoofed, HTTP_REFERER is generally a good way to make sure a visitor came from a certain pagewhether you want to use that to say, "You can't download my files because you came from another site" or "Welcome, Google users!" is up to you. The PATH_INFO element in $_SERVER is particularly interesting, because it allows you to grab directory information specified after the script. Consider this script: if (isset($_SERVER['PATH_INFO'])) { print "The page you requested was {$_SERVER['PATH_INFO']}<br />"; } else { print "You didn't request a page<br />"; } Save that code as pathinfo.php, then load it in your web browser. You will see You didn't request a page. Edit the URL, adding a filename onto the end of pathinfo.php. For example: www.yoursite.com/pathinfo.php/path/to/some/file.txt. Now when you load the page, you should see that extra path information printed out. This is commonly used in online filesystems, as it means that the URL required to get to a file is just the name of the script followed by the filename wanted.
The $_ENV variable contains environment variables in your system. On Windows, this usually includes variables like "OS" (probably set to "Windows_NT"), "WINDIR" (probably set to "C:\WINDOWS"), and so on. If you are using PHP on the command line, the $_SERVER superglobal will include all the variables from $_ENV. |