Tuesday, November 5, 2019

How to Use $_SERVER in PHP

How to Use $_SERVER in PHP $_SERVER is one of the PHP global variables- termed Superglobals- which contain information about server and execution environments. These are pre-defined variables so they are always accessible from any class, function or file. The entries here are recognized by web servers, but there is no guarantee that each web server recognizes every Superglobal. These three PHP $_SERVER arrays all behave in similar ways- they return information about the file in use. When exposed to different scenarios, in some cases they behave differently. These examples may help you decide which is best for what you need. A full list of $_SERVER arrays is available at the PHP website. $_SERVER[PHP_SELF] PHP_SELF is the name of the currently executing script. yoursite.com/example/ /example/index.phpyoursite.com/example/index.php   /example/index.phpyoursite.com/example/index.php?atest   /example/index.phpyoursite.com/example/index.php/dir/test   /dir/test When you use $_SERVER[’PHP_SELF’], it returns the file name /example/index.php both with and without the file name typed in the URL. When variables are appended at the end, they were truncated and again /example/index.php was returned. The only version that produced a different result has directories appended after the file name. In that case, it returned those directories. $_SERVER[REQUEST_URI] REQUEST_URI refers to the URI given to access a page. yoursite.com/example/   /yoursite.com/example/index.php   /example/index.phpyoursite.com/example/index.php?atest   /example/index.php?atestyoursite.com/example/index.php/dir/test   /example/index.php/dir/test All of these examples returned exactly what was entered for the URL. It returned a plain /, the file name, the variables, and the appended directories, all just as they were entered. $_SERVER[SCRIPT_NAME] SCRIPT_NAME is the current scripts path. This comes in handy for pages that need to point to themselves. yoursite.com/example/   /example/index.phpyoursite.com/example/index.php   /example/index.phpyoursite.com/example/index.php?atest   /example/index.phpyoursite.com/example/index.php/dir/test   /example/index.php All cases here returned only the file name /example/index.php regardless of whether it was typed, not typed, or anything was appended to it.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.