如何从URL地址获取文件夹名称

时间:2014-04-29 10:46:08

标签: php url

我网站的网址是:

http://mc.net46.net/ + folderName + fileName

例如:

http://mc.net46.net/mc/file01.php
http://mc.net46.net/mx/file05.php

folderName总是两个字符。

$address = 'http://mc.net46.net'.$_SERVER["REQUEST_URI"];

结果:http://mc.net46.net/mc/file01.php - 确定

$fname = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);

结果:file01.php - 确定

两个问题:

这是获取$ address和$ fname的正确方法吗?

如何获取folderName?

4 个答案:

答案 0 :(得分:5)

尝试以另一种方式获取动态文件名:

    <?php

    $fname = "http://mc.net46.net/mc/file01.php";
OR 
    $fname = $_SERVER["REQUEST_URI"];
    $stack = explode('/', $fname);
    $ss = end($stack);
    echo $ss;

    ?>

$fname您可以使用此$fname = explode('/', $_SERVER["REQUEST_URI"]);

答案 1 :(得分:2)

获取地址对我来说是正确的。但是,您可以使用explodearray_pop

轻松获取$ fname和文件夹名称
$stack = explode('/', $_SERVER["REQUEST_URI"]);
$fname = array_pop($stack);
$folderName = array_pop($stack);

修改

解释这是如何工作的:explode函数会将URI拆分为['', 'mc', 'file01.php']。现在函数array_pop从数组中取出最后一个元素($fname = 'file01.php'),这意味着在第一次调用之后,数组将是['', 'mc'],并且在第二次调用中重复相同的操作将将取出($folderName = 'mc')因为它将是数组中的最后一个元素并离开['']

答案 2 :(得分:1)

function getUriSegment($n) {
    $segs = explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
    return count($segs)>0 && count($segs)>=($n-1)?$segs[$n] : '';
}

// if the url is http://www.example.com/foo/bar/wow

echo getUriSegment(1); //returns foo
echo getUriSegment(2); //returns bar

了解更多信息: - http://www.timwickstrom.com/server-side-code/php/php-get-uri-segments/

答案 3 :(得分:1)

使用basename

$fname = basename("http://mc.net46.net/mc/file01.php")

 RESULT = file01.php 

DEMO