Reputation: 6693
I have a function that returns the current folder name:
function the_page_title()
{
$page_name = dirname(__FILE__);
$each_page_name = explode('/', $page_name);
$len_page_dir = count($each_page_name);
$c_i_p_n = 0;
while($len_page_dir != $c_i_p_n)
{
$c_i_p_n++;
}
echo $each_page_name[$c_i_p_n];
}
However, this returns what $page_name
holds and not the folder I am currently in.
When I print_r($each_page_name)
I get this:
Array ( [0] => [1] => home [2] => kyleport [3] => public_html [4] => inc ) /home/kyleport/public_html/inc
Could anyone point me in the right direction because I have no clue where this is going wrong :( Thank-you!
In this case, I want it to display inc
Upvotes: 1
Views: 4537
Reputation: 10450
Just to add my suggestion to this list.
If you simply want to get the current folder name. You could just use __DIR__
in combination with basename()
<?php $current_directory = basename(__DIR__); ?>
An example of structure and returned content, if the above was added to the file.php:
../directory-top/directory-sub/file.php
output > directory-sub
Upvotes: 0
Reputation: 11
This little line of code did it for me.
echo basename(getcwd())
;
I just got the name of the folder I was looking for.
Upvotes: 1
Reputation: 3569
As said before, you should use getcwd()
or, otherwise, your function will always return the folder where it's located instead of the current script directory.
Instead of explode, you could use basename
;
function the_page_title()
{
$page_name = getcwd(); // current script folder
return basename($page_name);
}
<title><?php echo the_page_title(); ?></title>
Upvotes: 2
Reputation: 1390
You can use;
echo getcwd();
This returns the current working directory on success, or FALSE
on failure.
Upvotes: 4
Reputation: 3886
You should be able to get the current directory with the predefined constant
__DIR__
which is the equivalent of
dirname(__FILE__)
so you should use
$each_page_name = explode('/', __DIR__);
$dir = end($each_page_name);
echo $dir;
Upvotes: 1
Reputation: 6693
I fixed my code:
function the_page_title()
{
$page_name = getcwd(); // getcwd() gets the directory of the file you call the function from
$each_page_name = explode('/', $page_name);
$len_page_dir = count($each_page_name) -1;
return $each_page_name[$len_page_dir];
}
use:
<title><?php echo the_page_title(); ?></title>
Upvotes: 0
Reputation: 3679
You just want the last element of an array:
$page_name = dirname(__FILE__);
$each_page_name = explode('/', $page_name);
echo end($each_page_name);
Upvotes: 5