在 PHP 中使用脚本时,我需要从服务器的角度和域 url 的角度知道其当前文件夹和路径是什么。
我还需要带或不带扩展名的文件名或脚本名称,以及带或不带任何参数传入的文件名或脚本名称。
例如,如果我调用以下内容:
https://example.com/somefolder/anotherfolder/test.php?hey=there
我想取回所有这些单独的部分:
test
test.php
test.php?hey=there
hey=there
https://example.com
/home/myserver/public_html
/somefolder/anotherfolder
Run Code Online (Sandbox Code Playgroud)
因此,这是我的通用解决方案,它将分解所有内容,然后允许您根据需要将所有内容重新组合在一起。
请参阅下面的输出,将脚本放在以下位置(然后调用它): https://example.com/somefolder/anotherfolder/test.php?hey =there
<?php
// filename only including extension but no path
$script_name_with_ext = basename(__FILE__);
// filename only with no extension and no path
$script_name_no_ext = basename(__FILE__, ".php");
// filename only including extension and all arguments but no path
$script_name_with_args = basename($_SERVER["REQUEST_URI"]);
// arguments only with no filename
$args_no_script_name = str_replace ( $script_name_with_ext."?" , "", $script_name_with_args);
// path portion only with no domain and no server portions
$path_only = pathinfo($_SERVER['PHP_SELF'], 1);
// domain url portion only with no path
$domain_no_path = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://{$_SERVER['HTTP_HOST']}";
// domain url including path
$domain_with_path = $domain_no_path.$path_only;
// domain url and path and filename with extension
$full_domain = $domain_with_path."/".$script_name_with_ext;
// server including path
$server_with_path = str_replace ("/".$script_name_with_ext , "", __FILE__);
// server only with no path
$server_no_path = str_replace($path_only, "", $server_with_path);
// server and path and filename with extension
$full_server = $server_with_path."/".$script_name_with_ext;
// output everything here
echo $script_name_no_ext."<br>";
echo $script_name_with_ext."<br>";
echo $script_name_with_args."<br>";
echo $args_no_script_name."<br><br>";
echo $path_only."<br><br>";
echo $server_no_path."<br>";
echo $server_with_path."<br>";
echo $full_server."<br>";
echo $full_server."?".$args_no_script_name."<br><br>";
echo $domain_no_path."<br>";
echo $domain_with_path."<br>";
echo $full_domain."<br>";
echo $full_domain."?".$args_no_script_name."<br><br>";
?>
Run Code Online (Sandbox Code Playgroud)
输出将如下所示:
test
test.php
test.php?hey=there
hey=there
/somefolder/anotherfolder
/home/myserver/public_html
/home/myserver/public_html/somefolder/anotherfolder
/home/myserver/public_html/somefolder/anotherfolder/test.php
/home/myserver/public_html/somefolder/anotherfolder/test.php?hey=there
https://example.com
https://example.com/somefolder/anotherfolder
https://example.com/somefolder/anotherfolder/test.php
https://example.com/somefolder/anotherfolder/test.php?hey=there
Run Code Online (Sandbox Code Playgroud)