How To Get The Currently Viewed URL In PHP
When you go about building your PHP scripts, you will soon find that there are many cases in which you need to know the current URL. PHP 5 comes loaded with several functions in which to do so, meaning that there will be very little programming on your part in the process.
There are multiple server variables that you can make use of to call the current URL based on what you need. Before we get started in reviewing them, first you should know that any server variable that works based on HTTP headers will potentially be a security concern. This is because HTTP can be faked, so do be sure to put in the correct security measures to circumvent this fact.
To easily find the current domain that the user is browsing, you can use the server variable named HTTP_HOST. This server variable is useful for building links to different parts of your website, or for using remote files for inclusion. This variable is going to allow you to call the domain in the format of “YourName.com”; you will have to concatenate onto this to properly build any links or pass this data onto other functions.
The SCRIPT_NAME server variable is also of great use, as it can find the actual path to the running script. This is most used to find the current location of the file so that the developer can make a link to the current page. This is mostly done for search engine optimization reasons, but also helps out in the overall ease of use of the application you are working on.
Perhaps one of the most useful of all server variables is the QUERY_STRING variable. This variable allows us to find the query string that lies within the URL, which comes directly after the ternary symbol. This allows developers to pass data from one script to another flawlessly. Just be sure to encode your URLs while doing this, or you may create security holes that will prove to be quite disastrous to your website or database.
Using mod rewrite in your “.htaccess” file is a great way to gain a new level of user satisfaction. Rewriting URLs helps visitors to remember the URL they are viewing by sanitizing them, which is also great for search engine optimization. The only bad part is that finding the actual name of the running file can be tough it is written over with mod rewrite. In such a case, just use REQUEST_URI.
Final Thoughts
Security should be a major concern when using server variables. Always remember to encode information that is being sent in front of the visitor’s view, and always sanitize any information you are putting into your database. Doing so will ensure bad users don’t ruin your website, and your aspirations as a webmaster.