URLs in Joomla: Difference between revisions

From Joomla! Documentation

Robbiej (talk | contribs)
other methods included
Robbiej (talk | contribs)
external and internal static urls included
Line 92: Line 92:
** <tt>Uri::base(true)</tt> returns the string "/mysite/administrator".
** <tt>Uri::base(true)</tt> returns the string "/mysite/administrator".


(This is similar to the [[https://docs.joomla.org/Constants#Difference_between_JPATH_SITE.2C_JPATH_ROOT.2C_and_JPATH_BASE | Joomla Path constants]]
(This is similar to the [[Constants#Difference_between_JPATH_SITE.2C_JPATH_ROOT.2C_and_JPATH_BASE|Joomla Path constants]]).


== Other URI methods ==
== Other URI methods ==
Line 123: Line 123:
<tt>$uri->toString(array('scheme','host','port','path');</tt>
<tt>$uri->toString(array('scheme','host','port','path');</tt>
</source>
</source>
== External URLs ==
Usually if you're including an external URL in your website you will just specify it as a string, but there may be occasions where using the Uri class to manipulate parts of a URL could be useful. In this case you can do something like
<source language="php">
$joomla = Uri::getInstance("//www.joomla.org");
$joomla->setScheme("https");
$joomla->setPath("/announcements");
$joomlaNews = $joomla->toString();  // https://www.joomla.org/announcements
echo "<a href='$joomlaNews'>Joomla news</a><br>";
</source>
Joomla uses the PHP [https://www.php.net/manual/function.parse-url.php parse-url] method to parse the URL, so you need to be careful with including appropriate slashes in the URL and path.
== Internal Static URLs ==
To output a URL link to a file within the Joomla instance use:
<tt>$url = Uri::root() . 'path/from/joomla/root/to/file.typ';</tt>
For example, to make a URL which points to a file picture.jpg in the Joomla images folder use:
<tt>$url = Uri::root() . 'images/picture.jpg';</tt>
The advantage of this approach is that no changes need to be made if you change the name of your joomla site or domain, such as moving from a development environment, via testing to live, and particularly if you want to display absolute URLs on your live site.

Revision as of 19:36, 18 December 2019

Introduction

This is one of a series of API Guides, which aim to help you understand how to use the Joomla APIs through providing detailed explanations and sample code which you can easily install and run.

This guide covers use of the JUri class (now known as Uri) and the use of the JRoute::_() method (now called Route). The Uri class enables you get the URL of the current webpage, and access parts of the URL. JRoute::_() is used to set up links to other webpage resources within your Joomla site.

Getting the current URL

To get the URL of the current webpage do:

use Joomla\CMS\Uri\Uri;
$uri = Uri::getInstance();
$url = $uri->toString();

The advantage of using this method is that it handles any peculiarities of the webserver (eg Apache or IIS) and also performs some cleaning of the URL to avoid some types of injection attacks.

What get returns from Uri::getInstance() isn't a PHP string of the URL, but rather a Joomla Uri object, which also holds internally the various parts of the URL, and provides getter and setter methods to read or write these URL parts as shown below.

     http://fredbloggs:itsasecret@www.example.com:8080/path/to/Joomla/index.php?task=view&id=32#anchorthis
     \__/   \________/ \________/ \_____________/ \__/\_______________________/ \_____________/ \________/
      |          |         |              |        |              |                    |            |
   scheme      user       pass          host      port          path                 query       fragment

The example column in the following table illustrates the result of each of the get methods on the URI above, all of which are strings.

Get method Set method Description Example
getFragment setFragment Fragment (everything after the '#'). This is often referred to as an anchor. anchorthis
getHost setHost Hostname or IP address. For example, 'www.joomla.org' or '192.168.2.45'. www.example.com
getPass setPass Password part of the authority. Don't use this! itsasecret
getPath setPath Path string. Note that the path always includes the leading "/" character. /path/to/Joomla/index.php
getPort setPort Port number. Specific schemes (protocols) have their own defaults (for example, 'http' is port 80, 'ftp' is port 21). 8080
getQuery setQuery Query in string format. For example, "foo=bar&x=y". task=view&id=32
getScheme setScheme Scheme (protocol). For example, 'http', 'https', 'ftp'. http
getUser setUser Username part of the authority. Don't use this! fredbloggs
getVar setVar An individual query item value from within the query part. A query parameter may be removed using delVar. 32

(Note that passing the user/password in the URL in this fashion is generally deprecated and not recommended, and won't work on some browsers. In this guide below it's not considered.)

root() and base()

base() and root() are static functions which return key URLs.

Uri::root($pathonly) is a static function which returns the URL to the root of the Joomla site. It may or may not be the same as the HTTP domain, depending upon how your webserver is configured. In the common case where a Joomla instance "mysite" is installed in a directory under the webserver document root you are likely to get:

The second parameter to Uri::root(), namely $path, sets the path locally within the Uri class, and will get used in subsequent invocations of Uri::root(). Hence it's strongly advised that you don't set this parameter, as it could seriously muck up your website.

Uri::base($pathonly) is similar to Uri::root() but what is returned depends on whether it's called from the site application or the administrator application.

  • If you are on the site Uri::base() returns the same as Uri::root()
  • If you are on the admin back-end Uri::base() returns Uri::root() plus "administrator", so using the example above:

(This is similar to the Joomla Path constants).

Other URI methods

As well as the methods above, the Joomla Uri provides the methods listed below. In the following example code snippets, $uri refers to a Uri instance, obtained for example through $uri = Uri::getInstance();.

  • toString(array $parts = array('scheme', 'user', 'pass', 'host', 'port', 'path', 'query', 'fragment')) : string

toString() converts the Uri to a string, and allows you to select the parts of the URL which you want, eg

$uri->toString(array('scheme','host','port','path');

will return the URL minus any query or anchor (fragment).

  • render() is similar to toString()/ in that it returns the parts of the URL you want, but as you have to pass the parts you want as a bitmask, it's preferable to use toString() instead.
  • isSsl() returns true if the scheme is https, false otherwise, eg

$secure = $uri->isSsl();

  • isInternal() returns true if the URL is within the Joomla instance (including the administrator area), false otherwise. Note that this is a static function, and you pass the URL as a string, eg

$internal = Uri::isInternal("myurl.org");

  • current() returns the URL of the current page, minus any query string or fragment, eg

$currentURL = Uri::current();

and is basically equivalent to

<tt>$uri = Uri::getInstance();</tt>
<tt>$uri->toString(array('scheme','host','port','path');</tt>

External URLs

Usually if you're including an external URL in your website you will just specify it as a string, but there may be occasions where using the Uri class to manipulate parts of a URL could be useful. In this case you can do something like

$joomla = Uri::getInstance("//www.joomla.org");
$joomla->setScheme("https");
$joomla->setPath("/announcements");
$joomlaNews = $joomla->toString();  // https://www.joomla.org/announcements
echo "<a href='$joomlaNews'>Joomla news</a><br>";

Joomla uses the PHP parse-url method to parse the URL, so you need to be careful with including appropriate slashes in the URL and path.

Internal Static URLs

To output a URL link to a file within the Joomla instance use:

$url = Uri::root() . 'path/from/joomla/root/to/file.typ';

For example, to make a URL which points to a file picture.jpg in the Joomla images folder use:

$url = Uri::root() . 'images/picture.jpg';

The advantage of this approach is that no changes need to be made if you change the name of your joomla site or domain, such as moving from a development environment, via testing to live, and particularly if you want to display absolute URLs on your live site.