Last Updated: October 18, 2020
·
915
· projectcleverweb

Make URI's Easier To Work With

I have noticed that URI's can be a real pain to work with in PHP sometimes. For example, lets say you want to add a query variable, to a user-added URI. Pretty simple idea right? Well lets look at what you would have to do (in code) in order to accomplish that:

  • Make sure the users input is actually a valid URI
  • Check if there is already a query string (if so you'll need to find a way to preserve it, or you have to remove it completely.)
  • Make sure there isn't a fragment attached to the end of your query string. (you might need to preserve that too)
  • If the variable you want to write to already exists, do you want to override it or rename it?
  • Rebuild the query string, and put it back in the URI

And all of that is really just silly, considering that using and modifying URI's is a pretty standard thing in just about any PHP application. I mean why isn't it as simple as:

$uri = new uri($user_input);
if (empty($uri->error)) {
  $uri->query_add('myVar', 'myValue');
} else {
  // invalid URI error
}

Well now it is :)

Thanks to the PHP-URI library, modifying and gathering information on just about any URI is really simple.

A Couple Examples:

Daisy Chaining Operations

$uri = new uri('example@gmail.com');

// Quick and easy email template URI
$uri->chain()
    ->replace('SCHEME', 'mailto:')
    ->query_replace('subject', 'Re: [Suggestion Box]')
    ->query_replace('body', 'More snickers in the break room please!')
;
printf('<a href="%1$s">%2$s</a>', $uri, $uri->authority);

output:

<a href="mailto:example@gmail.com?subject=Re%3A%20%5BSuggestion%20Box%5D&body=More%20snickers%20in%20the%20break%20room%20please%21">example@gmail.com</a>

Gathering Information

$uri = new uri('http://example.com/path/to/file.ext?q=1');

switch ($uri->scheme_name) {
  case 'https':
  case 'sftp':
  case 'ssh':
    echo 'Uses SSL'.PHP_EOL;
    break;

  default:
    echo 'Does not use SSL'.PHP_EOL;
}

// Change to an absolute path
$abs_path = $_SERVER['DOCUMENT_ROOT'].$uri->path;
echo $abs_path.PHP_EOL;

// easier to read links
printf('<a href="%1$s">%2$s</a>', $uri->str(), $uri->host.$uri->path);

// FTP logins
$uri = new uri('ftp://jdoe@example.com/my/home/dir');
$login = array(
    'username' => $uri->user,
    'password' => $user_input,
    'domain'   => $uri->host,
    'path'     => $uri->path
);

output:

Does not use SSL
/var/www/path/to/file.ext
<a href="http://example.com/path/to/file.ext?q=1">example.com/path/to/file.ext</a>

About The Project

The Github Repo

Build Status Code Coverage Scrutinizer Code Quality License

Features

  • Highly Accurate Parser (based of the URI standard)
  • Easy String Operations
  • Easy Query Operations
  • Synchronized Variables
  • Daisy Chaining Operations
  • Handy Aliases
  • Composer Installation
  • 100% Code Coverage