Thursday, June 3, 2010

PHP - trimming off characters after the last slash in a URL

I really don't like programming. But every once in a while you've got to break down and do it for special projects. Recently I had to write some PHP code for a specific situation where I needed to be able to take the current URL the script was running at, strip out the script name, strip out the last slash and the directory name that proceeded it. Effectively, I was simulating ../ on the path because security requirements were getting in the way of a script. I played around with rtrim(), dirname(), regular expressions, etc but just wasn't quite getting the result that I wanted. My script determines the current URL, explodes it into a string array spliced at each slash character, then builds the new URL in a loop. You can tweak the iterations of the loop for however many directory levels back you want to go.

<?php
# Using SCRIPT_NAME

$path = $_SERVER['SCRIPT_NAME'];
$path2 = "/";
$domain = $_SERVER['HTTP_HOST'];

#echo "current path: " .$path . "<br>";
$parts = explode("/",$path); // splice by slash

$i=1; // skip zero cuz it's empty
$endi = count($parts) - 2; // number of parts minus 2 hierarchy

while ($i < $endi) {
$path2 = $path2 . $parts[$i] . "/";
$i++;
}
$temp = 'http://' . $domain . $path2;
echo $temp;

?>



Example:
If you run the above code and your original URL was http://www.test.com/blue/test.php
the output would be http://www.test.com/

No comments: