NYCPHP Meetup

NYPHP.org

[nycphp-talk] Best practices for combining paths?

Chris Snyder chsnyder at gmail.com
Tue Mar 31 16:46:38 EDT 2009


On Mon, Mar 30, 2009 at 5:22 PM, Paul A Houle <paul at devonianfarm.com> wrote:
> I pretty frequently write code like
>
> $url_base="http://somesite.com/system/controller";
> $path="object_type/verb.modifier/object_id";
> $url="{$url_base}/{$path}";
>
> note that this working correctly depends sensitively on how paths are used,
>  for instance,  if somebody puts a slash at the end of $url_base,  you wind
> up with a double slash in the path.  That doesn't usually have a disasterous
> effect,  but I'm a stickler about url canonicalizaton.
>
> My question is,  am I missing a good PHP built-in for combining parts of
> URLs or filesystem paths?  Is there a good library I should use?
>

This is the kind of thing where writing your own is annoying but easy.

function combine_paths( $path1, $path2 ) {
  if ( substr( $path1, -1 ) != '/' ) {
    $path1 .= '/';
  }
  if ( substr( $path2, 0, 1 ) == '/' ) {
    $path2 = substr( $path2, 1 );
  }
  return $path1.$path2;
}

Does it need to be any more complicated than that?



More information about the talk mailing list