Webemania | How to Get Current Page URL in php

| Published Date: 11 Aug 2014 | Last Updated Date: 04 Sep 2017
Total Reads: 2,935 | Last Visit: 22 Sep 2017 04:55:01 AM

  1. <?php
  2. // to get current page url, write echo get_current_page_url();
  3. function get_current_page_url() {
  4. $page_url = 'http';
  5. if ($_SERVER['HTTPS'] == 'on') {
  6. $page_url .= 's';
  7. }
  8. $page_url .= '://';
  9.  
  10. if ($_SERVER['SERVER_PORT'] != '80') {
  11. $page_url .= $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI'];
  12. }
  13. else {
  14. $page_url .= $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
  15. }
  16. return $page_url;
  17. }
  18. ?>

Why do you need to show the port number?

If the web server is not being addressed on a standard port, it would be necessary to include it in a URL in order to point to the correct service on the machine hosting the web server. Browsers and other HTTP clients pretty much assume port :80 as a default. SSL clients pretty much assume port :443 as a default.

That said, the code should be checking not only for port :80, but also port :443 to determine whether to omit the port number. As the code is now, it would unnecessarily add port :443 to all SSL requests.

Tags

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
Max length 128 characters
Image CAPTCHA
Enter the characters shown in the image.

About This Mania

Hasan Hafiz, Blogger at web mania ltd (www.webemania.com). He has more than 5 years experience in web development platform. He worked as a Sr. Software Developer at Canadian based outsourcing software firm, Lead Developer at countries top most VOIPswitch development company and Sr. Software Engineer at USA based outsourcing software firm . His expertise areas are PHP, MySQL, CSS, Javascript, JQuery, HTML, XML and MVC Framework Codeigniter. He has been along with Drupal from more than 4 years. You may call him Drupal Addicted.