joinPath() - Combines Multiple Path Fragments
This function will combine all the path fragments provided as the argument and return the result. joinPath() will use the correct path separator for the current platform.
Arguments
Each argument is a fragment of the result path. You can provide as many arguments as needed.Example
joinPath("/var/", "www", "html", "index.php");
- Returns /var/www/html/index.php
joinPath("/var/", "/www/", "html/", "index.php");
- Returns /var/www/html/index.php - excess '/' are not an issue
joinPath("/var/", "/www/", "", "html/", "", "index.php");
- Again, returns /var/www/html/index.php - empty fragments are handled correctly
Code
<?php
/**
* Takes one or more file names and combines them, using the correct path separator for the
* current platform and then return the result.
* Example: joinPath('/var','www/html/','try.php'); // returns '/var/www/html/try.php'
* Link: http://www.bin-co.com/php//scripts/filesystem/join_path/
*/
function joinPath() {
$path = '';
$arguments = func_get_args();
$args = array();
foreach($arguments as $a) if($a !== '') $args[] = $a;//Removes the empty elements
$arg_count = count($args);
for($i=0; $i<$arg_count; $i++) {
$folder = $args[$i];
if($i != 0 and $folder[0] == DIRECTORY_SEPARATOR) $folder = substr($folder,1); //Remove the first char if it is a '/' - and its not in the first argument
if($i != $arg_count-1 and substr($folder,-1) == DIRECTORY_SEPARATOR) $folder = substr($folder,0,-1); //Remove the last char - if its not in the last argument
$path .= $folder;
if($i != $arg_count-1) $path .= DIRECTORY_SEPARATOR; //Add the '/' if its not the last element.
}
return $path;
}