Last active
December 31, 2015 04:39
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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