Working with URIs

    Creating a URI instance is as simple as creating a new class instance:

    Alternatively, you can use the function to return an instance for you:

    1. $uri = service('uri');

    When you create the new instance, you can pass a full or partial URL in the constructor and it will be parsedinto its appropriate sections:

    1. $uri = new \CodeIgniter\HTTP\URI('http://www.example.com/some/path');
    2. $uri = service('uri', 'http://www.example.com/some/path');

    Many times, all you really want is an object representing the current URL of this request. This can be accessedin two different ways. The first is to grab it directly from the current request object. Assuming that you’re ina controller that extends CodeIgniter\Controller you can get it like:

      Second, you can use one of the functions available in the url_helper:

      1. $uri = current_url(true);

      You must pass true as the first parameter, otherwise, it will return the string representation of the current URL.

      Many times, all you really want is to get a string representation of a URI. This is easy to do by simply castingthe URI as a string:

      1. $uri = current_url(true);
      2. echo (string)$uri; // http://example.com

      If you know the pieces of the URI and just want to ensure it’s all formatted correctly, you can generate a stringusing the URI class’ static createURIString() method:

      1. $uriString = URI::createURIString($scheme, $authority, $path, $query, $fragment);
      2.  
      3. // Creates: http://exmample.com/some/path?foo=bar#first-heading
      4. echo URI::createURIString('http', 'example.com', 'some/path', 'foo=bar', 'first-heading');

      Once you have a URI instance, you can set or retrieve any of the various parts of the URI. This section will providedetails on what those parts are, and how to work with them.

      Scheme

      The scheme is frequently ‘http’ or ‘https’, but any scheme is supported, including ‘file’, ‘mailto’, etc.

      1. $uri = new \CodeIgniter\HTTP\URI('http://www.example.com/some/path');
      2.  
      3. echo $uri->getScheme(); // 'http'
      4. $uri->setScheme('https');

      Authority

      Many URIs contain several elements that are collectively known as the ‘authority’. This includes any user info,the host and the port number. You can retrieve all of these pieces as one single string with the getAuthority()method, or you can manipulate the individual parts.

      1. echo $uri->getAuthority(); // user@example.com:21
      2. echo $uri->showPassword()->getAuthority(); // user:password@example.com:21
      3.  
      4. // Turn password display off again.
      5. $uri->showPassword(false);

      If you do not want to display the port, pass in as the only parameter:

      1. echo $uri->getAuthority(true); // user@example.com

      Note

      If the current port is the default port for the scheme it will never be displayed.

      The userinfo section is simply the username and password that you might see with an FTP URI. While you can getthis as part of the Authority, you can also retrieve it yourself:

      1. echo $uri->getUserInfo(); // user

      By default, it will not display the password, but you can override that with the showPassword() method:

      1. echo $uri->showPassword()->getUserInfo(); // user:password
      2. $uri->showPassword(false);

      Host

      The host portion of the URI is typically the domain name of the URL. This can be easily set and retrieved with thegetHost() and setHost() methods:

      1. $uri = new \CodeIgniter\HTTP\URI('http://www.example.com/some/path');
      2.  
      3. echo $uri->getHost(); // www.example.com
      4. echo $uri->setHost('anotherexample.com')->getHost(); // anotherexample.com

      Port

      The port is an integer number between 0 and 65535. Each sheme has a default value associated with it.

      1. $uri = new \CodeIgniter\HTTP\URI('ftp://user:password@example.com:21/some/path');
      2.  
      3. echo $uri->getPort(); // 21
      4. echo $uri->setPort(2201)->getPort(); // 2201

      When using the setPort() method, the port will be checked that it is within the valid range and assigned.

      The path are all of the segments within the site itself. As expected, the getPath() and methodscan be used to manipulate it:

      1. $uri = new \CodeIgniter\HTTP\URI('http://www.example.com/some/path');
      2. echo $uri->getPath(); // 'some/path'
      3. echo $uri->setPath('another/path')->getPath(); // 'another/path'

      Note

      When setting the path this way, or any other way the class allows, it is sanitized to encode any dangerouscharacters, and remove dot segments for safety.

      Query

      Note

      Query values cannot contain fragments. An InvalidArgumentException will be thrown if it does.

      You can set query values using an array:

      1. $uri->setQueryArray(['foo' => 'bar', 'bar' => 'baz']);

      The setQuery() and setQueryArray() methods overwrite any existing query variables. You can add a value to thequery variables collection without destroying the existing query variables with the addQuery() method. The firstparameter is the name of the variable, and the second parameter is the value:

      1. $uri->addQuery('foo', 'bar');

      Filtering Query Values

      You can filter the query values returned by passing an options array to the getQuery() method, with either anonly or an except key:

      1. $uri = new \CodeIgniter\HTTP\URI('http://www.example.com?foo=bar&bar=baz&baz=foz');
      2.  
      3. // Returns 'foo=bar'
      4. echo $uri->getQuery(['only' => ['foo']);
      5.  
      6. // Returns 'foo=bar&baz=foz'
      7. echo $uri->getQuery(['except' => ['bar']]);

      This only changes the values returned during this one call. If you need to modify the URI’s query values more permanently,you can use the stripQuery() and methods to change the actual object’s query variable collection:

      1. $uri = new \CodeIgniter\HTTP\URI('http://www.example.com?foo=bar&bar=baz&baz=foz');
      2.  
      3. // Leaves just the 'baz' variable
      4. $uri->stripQuery('foo', 'bar');
      5.  
      6. // Leaves just the 'foo' variable
      7. $uri->keepQuery('foo');

      Fragment

      Fragments are the portion at the end of the URL, preceded by the pound-sign (#). In HTML URL’s these are linksto an on-page anchor. Media URI’s can make use of them in various other ways.

      1. $uri = new \CodeIgniter\HTTP\URI('http://www.example.com/some/path#first-heading');
      2.  
      3. echo $uri->getFragment(); // 'first-heading'
      4. echo $uri->setFragment('second-heading')->getFragment(); // 'second-heading'

      Each section of the path between the slashes is a single segment. The URI class provides a simple way to determinewhat the values of the segments are. The segments start at 1 being the furthest left of the path.

      1. // URI = http://example.com/users/15/profile
      2.  
      3. // Prints '15'
      4. if ($request->uri->getSegment(1) == 'users')
      5. {
      6. echo $request->uri->getSegment(2);
      7. }

      You can get a count of the total segments:

        Finally, you can retrieve an array of all of the segments: