Skip to content

Instantly share code, notes, and snippets.

@SirTony
Last active December 31, 2015 04:39
Show Gist options
  • Save SirTony/7935732 to your computer and use it in GitHub Desktop.
Save SirTony/7935732 to your computer and use it in GitHub Desktop.
Combines segments of a filesystem path into an absolute path using the system's directory separator char, and supports checking for illegal characters on Windows systems. The path() function also supports multi-dimensional arrays.
<?php
function path()
{
// Determine if we are one windows, And get our path parts
$IsWindows = strtoupper( substr( PHP_OS, 0, 3 ) ) === "WIN";
$args = func_get_args();
$parts = array();
// Trim our paths to remove spaces and new lines
foreach( $args as $part )
$parts[] = is_array( $part ) ? trim( implode_recursive( DIRECTORY_SEPARATOR, $part ) ) : trim( $part );
// Get our cleaned path into a variable with the correct directory seperator
$newPath = implode( DIRECTORY_SEPARATOR, $parts );
// Do some checking for illegal path chars
if( $IsWindows )
{
$Pattern = "~[\\/:?*\"<>|\r\n]+~";
$tempPath = preg_replace( "~^[A-Z]{1}:~", "", $newPath );
$tempPath = trim( $tempPath, DIRECTORY_SEPARATOR );
$tempPath = explode( DIRECTORY_SEPARATOR, $tempPath );
foreach( $tempPath as $part )
{
if( preg_match( $Pattern, $part ) )
throw new Exception( "Illegal characters in path." );
}
}
return realpath( $newPath );
}
function implode_recursive( $sep, $array )
{
$imploded = "";
foreach( $array as $item )
{
if( is_array( $item ) )
$imploded = implode_recursive( $sep, $item ) . $sep;
else
$imploded = $item . $sep;
}
return rtrim( $imploded, $sep );
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment