Brandrally
Brandrally

Reputation: 851

Retrieving URL folder name from string

I am having a slight trouble. I am wanting to get a find the top level folder and use it as a variable.

For instance.

If I have a url: http://www.someurl.com/foldername/hello.php

I would like to look at the URL and echo 'foldername'.

At present my code strips things so that it echos 'hello.php'.

Any help would be greatly appreciated.

<?php

// Get URL String // 
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}

// Split String and get folder//

function curPageName() {
return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/"));
}

// Pass along Results //
$foldername = curPageName();

echo $foldername;

?>

Upvotes: 1

Views: 2914

Answers (3)

Rinzler
Rinzler

Reputation: 2116

          <?php 

            $a = "http://www.someurl.com/foldername/hello.php";

            $b =  explode('/',$a);

            //var_dump($b); 

        // i got this result  array(5) { [0]=> string(5) "http:" [1]=> string(0) "" [2]=>                  string(15) "www.someurl.com" [3]=> string(10) "foldername" [4]=> string(9) "hello.php" }

// now to get or echo foldername store the value from the array in a variable

         $value = $b['3'];

        echo $value // will output foldername 
      ?>

i am a newbie too

Upvotes: 1

Kris
Kris

Reputation: 8868

Should we do so tough?

i think this would do

function getFolderName($URL)
{
        $pieces  = explode("/",$URL);
    //    return $pieces[3];// -->do this if you  need folder after domain
    return $pieces[count($pieces)-2]; //-->do this if you need folder just before sourcefile
}

Upvotes: 1

dan-lee
dan-lee

Reputation: 14492

Try it with

$parse = parse_url('http://www.someurl.com/foldername/hello.php')
echo dirname($parse['path']);
// Output: /foldername
// use trim() to strip of that leading slash

Upvotes: 1

Related Questions