Created
December 15, 2015 18:02
-
-
Save kasparsd/ad25a824506e99b0a8cf to your computer and use it in GitHub Desktop.
Normalize relative path to absolute path
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 normalize_url( $url ) { | |
$delete = 0; | |
$index = 0; | |
$parts = explode( '/', $url ); | |
foreach ( $parts as $p => $part ) { | |
if ( '..' === $part ) { | |
$delete++; | |
$index++; | |
} elseif ( $delete ) { | |
$offset = $index - $delete * 2; | |
// Negative offset means an incorrect path | |
if ( 0 === $offset ) { | |
$index++; | |
$delete = 0; | |
} else { | |
array_splice( $parts, $offset, $delete * 2 ); | |
$index -= $delete; | |
$delete = 0; | |
} | |
} else { | |
$index++; | |
} | |
} | |
return implode( '/', $parts ); | |
} | |
$test = array( | |
'http://kaspars.net/one/about/two/../three/another/../../style.css' => 'http://kaspars.net/one/about/style.css', | |
'http://kaspars.net/theme/../style.css' => 'http://kaspars.net/style.css', | |
'/home/folder/../style.css' => '/home/style.css', | |
'./home/../style.css' => './style.css', | |
'/home/subfolder/../../../toomuch/style.css' => '/home/subfolder/../../../toomuch/style.css', | |
); | |
$results = array(); | |
foreach ( $test as $url => $expected ) { | |
$results[ $url ] = normalize_url( $url ); | |
} | |
$errors = array_diff_assoc( $results, $test ); | |
print_r( $errors ); // should be empty |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment