我在我的网站上的一个文件夹里有一个php页面。
我需要将当前目录的名称添加到一个变量中,例如:
$myVar = current_directory_name;
这个是可能的吗?
发布于 2012-04-04 00:21:37
getcwd();
或
dirname(__FILE__);
或(PHP5)
basename(__DIR__)
http://php.net/manual/en/function.getcwd.php
http://php.net/manual/en/function.dirname.php
您可以使用basename()
来获取路径的结尾部分:)
在你的例子中,我会说你很可能想要使用getcwd()
,当你有一个需要包含另一个库并且包含在另一个库中的文件时,dirname(__FILE__)
更有用。
例如:
main.php
libs/common.php
libs/images/editor.php
在common.php
中,您需要使用editor.php
中的函数,因此您可以使用
common.php
require_once dirname(__FILE__) . '/images/editor.php';
main.php
require_once libs/common.php
这样,当common.php在main.php
中为require'd
时,common.php
中的require_once
调用将正确地将editor.php
包含在images/editor.php
中,而不是尝试查看运行main.php
的当前目录。
发布于 2014-08-01 13:31:02
要仅获取执行脚本的目录的名称:
//Path to script: /data/html/cars/index.php
echo basename(dirname(__FILE__)); //"cars"
发布于 2013-03-14 18:35:45
您可以使用dirname(__FILE__)
获取当前文件所在目录的路径。
示例:/path_to/your_dir/your_file.php
// use dirname to get the directory of the current file
$path = dirname(__FILE__);
// $path here is now /path_to/your_dir
// split directory into array of pieces
$pieces = explode(DIRECTORY_SEPARATOR, $path);
// $pieces = ['path_to', 'your_dir']
// get the last piece
echo $pieces[count($pieces) - 1];
// result is: your_dir
https://stackoverflow.com/questions/9997391
复制相似问题