How to get the full URL of a Drupal page?

2019-01-30 10:26发布

问题:

I need to be grabbing the URL of the current page in a Drupal site. It doesn't matter what content type it is - can be any type of node.

I am NOT looking for the path to theme, or the base url, or Drupal's get_destination. I'm looking for a function or variable that will give me the following in full:

http://example.com/node/number

Either with or without (more likely) the http://.

回答1:

drupal_get_destination() has some internal code that points at the correct place to getthe current internal path. To translate that path into an absolute URL, the url() function should do the trick. If the 'absolute' option is passed in it will generate the full URL, not just the internal path. It will also swap in any path aliases for the current path as well.

$path = isset($_GET['q']) ? $_GET['q'] : '<front>';
$link = url($path, array('absolute' => TRUE));


回答2:

This is what I found to be useful

global $base_root;
$base_root . request_uri();

Returns query strings and it's what's used in core: page_set_cache()



回答3:

You can also do it this way:

$current_url = 'http://' .$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

It's a bit faster.



回答4:

Try the following:

url($_GET['q'], array('absolute' => true));


回答5:

This method all is old method, in drupal 7 we can get it very simple

    current_path()
  • http://example.com/node/306 returns "node/306".
  • http://example.com/drupalfolder/node/306 returns "node/306" while base_path() returns "/drupalfolder/".
  • http://example.com/path/alias (which is a path alias for node/306) returns "node/306" as opposed to the path alias.

and another function with tiny difference

request_path()
  • http://example.com/node/306 returns "node/306".
  • http://example.com/drupalfolder/node/306 returns "node/306" while base_path() returns "/drupalfolder/".
  • http://example.com/path/alias (which is a path alias for node/306) returns "path/alias" as opposed to the internal path.
  • http://example.com/index.php returns an empty string (meaning: front page).
  • http://example.com/index.php?page=1 returns an empty string.


回答6:

I find using tokens pretty clean. It is integrated into core in Drupal 7.

<?php print token_replace('[current-page:url]'); ?>


回答7:

The following is more Drupal-ish:

url(current_path(), array('absolute' => true)); 


回答8:

For Drupal 8 you can do this :

$url = 'YOUR_URL';
$url = \Drupal\Core\Url::fromUserInput('/' . $url,  array('absolute' => 'true'))->toString();


回答9:

Maybe what you want is just plain old predefined variables.

Consider trying

$_SERVER['REQUEST_URI'']

Or read more here.