Home > Software design >  get the full url name
get the full url name

Time:07-23

I am trying to get the full url name for example

https://example.com/index.php?page=home

I use this code

$curPageName = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/") 1);

and this code

<a href="https://example.com/<?php echo $curPageName; ?>" title="Check this site in English">

Unfortunately the result comes out as

https://example.com/index.php

the rest or url "?page=home" is missing. How can I get this included? its not just only one page like ?page=home is has more pages. Do I miss something in substr($_SERVER["SCRIPTNAME"] ???

CodePudding user response:

Use $_SERVER['QUERY_STRING'] to get the query string and make a function that inserts a ? if there are indeed values in the query.

function get_query_string() {
   $query = $_SERVER['QUERY_STRING'];
   if(strlen($query) > 0) {
      $query = "?" . $query;
   }
   return $query;
}
$curPageName = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/") 1) . get_query_string();


CodePudding user response:

Use $_SERVER['REQUEST_URI']

https://google.com/foo/bar/?test=3

returns

/foo/bar/?test=3

In a link: <a href="https://example.com<?php echo $_SERVER['REQUEST_URI']; ?>" title="Link">

A few notes about using this:

  1. Be aware that the client can set REQUEST_URI to any value
  2. REQUEST_URI might include the scheme and domain when calling the page through stream_context_create() with a HTTP header of 'request_fulluri' set to 1.

Additional Questions:

  1. How do I capture the whole URL using PHP?
  2. Get the full URL in PHP
  • Related