PHP:如何仅获取网站的当前文件夹


PHP: How to get only the current folder of a website

例如,我有一个网站指向这样的页面:

http://www.mysite.com/folder/file

我怎样才能确定/文件夹,以便我可以进一步引用 if 语句,例如

if /folder then echo something

我为什么需要这个?

我试图告诉Facebook从页面中选择哪个图像。实际上,我有一个非常简单的页面结构,Facebook应该拍摄的图像总是首先,但不知何故,它确实会不时选择另一个。我猜是因为其他图像加载得更快。rel="img_src" 的旧方法似乎不再有效,因为我可以将其添加到想要的图像中。

当然,我使用开放图协议来告诉Facebook它应该使用哪个图像。

正在使用cms,我可以根据图像具有的id输出图像的路径。对于位于两个不同文件夹中的不同类型的页面,我有两个不同的 id。

这导致:

if index --> echo meta og for index img
else if /folderone (with id1) --> echo meta og for id1
else if /foldertwo (with id2) --> echo meta og for id2

这就是为什么我需要知道文件夹名称的原因。

现在有了答案,我有以下设置,只是你知道:

<?php $folder = dirname($_SERVER['SCRIPT_NAME']); ?>
<?php if (dirname($_SERVER['SCRIPT_NAME']) == "/") echo "<meta property='og:image' content='http://www.mysite.com/img/img.jpg'/>" ;?>
<?php if (dirname($_SERVER['SCRIPT_NAME']) == "/folderOne") echo "<meta property='og:image' content='http://www.mysite.com/img/{$img_id1}'/> " ;?>
<?php if (dirname($_SERVER['SCRIPT_NAME']) == "/folderTwo") echo "<meta property='og:image' content='http://www.mysite.com/img/{$img_id2}'/> " ;?>

parse_url &爆炸

$path = parse_url($url, PHP_URL_PATH);

给你

/folder/file

然后你可以 explode() 来分隔路径值并检查第一个以查看它是否是"文件夹"

此处的示例:http://tehplayground.com/#7TIKAwp6J示例代码:

$url = "http://www.mysite.com/folder/file";
$path = parse_url($url, PHP_URL_PATH);
$arr = explode("/",$path);
echo $arr[1]; // leading slash makes [0] ""

输出

文件夹

$script = $_SERVER['SCRIPT_NAME'];
echo dirname($script);

可能使用"获取当前工作目录"函数getcwd()

  1. 通过目录分隔符将其分解。
  2. 然后像这样抓取最后一个元素:

    $var = getcwd();
    $var = explode('''', $var); // your OS might use '/' instead
    $var = end($var);
    

我想这假设您没有使用某种使用路由的 MVC 框架。

我希望这有所帮助!

我认为这比爆炸字符串更好:

function getCurrentDirectory(){
    $curDirPath = getcwd();
    return substr($curDirPath, strrpos($curDirPath, '/') + 1);
}

getcwd()为您提供当前目录的路径,然后您可以在其文件路径中最后一次出现/之后立即截断它。

$dir_list = explode('/', dirname($_SERVER['SCRIPT_FILENAME']));
$this_folder = $dir_list[count($dir_list)-1];
...
if ($this_folder) == "folderOne") echo "...."
...
if(dirname('yoursite/folder')){