使用由 PHP 文件创建的文件获取当前页面名称


Get current page name with file created by a PHP file

所以我有一个名为create.php的页面,它创建了另一个名为"1"的php文件。在这个名为"1"的 php 文件中。我希望使用

<?php echo $_SERVER['PHP_SELF'];?>

<?php $path = $_SERVER["SCRIPT_NAME"];echo $path;?>

创建一个链接,该链接将获取页面编号并+1它。当我执行这两个函数而不是获得我认为会得到的"1"时,我得到了"create",即创建它的页面。我对为什么会发生这种情况感到目瞪口呆,代码绝对在"1"上,我什至仔细检查以确保 create 制作了一个文件并且我在上面,那么为什么它认为当前页面是"创建"?

正在使用的代码

<?php
// start the output buffer
ob_start(); ?>
<?php echo $_SERVER['PHP_SELF'];?>
<?php
// open the cache file "cache/1" for writing
$fp = fopen("cache/1", 'w');
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
?>

您将代码分成几部分,您可能对会发生什么以及将用cache/1编写的内容有错误的想法。您的代码与以下内容相同:

<?php
// start the output buffer
ob_start();
// echo the path of the current script
echo $_SERVER['PHP_SELF'];
// open the cache file "cache/1" for writing
$fp = fopen("cache/1", 'w');
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();

我删除了结束的PHP标签(?>),当它后面跟着一个打开的PHP标签(<?php)。

现在应该清楚的是,如果没有输出缓冲,脚本create.php显示其相对于文档根目录的路径。输出缓冲捕获输出并将其放入文件cache/1 中。

您甚至不需要为此进行输出缓冲。您可以简单地删除对ob_*函数的所有调用,删除echo()行并使用:

fwrite($fp, $_SERVER['PHP_SELF']);

很明显,这不是你的目标。您可能希望生成包含以下内容的 PHP 文件:

<?php echo $_SERVER['PHP_SELF'];?>

这就像将文本放入字符串并将字符串写入文件一样简单:

<?php
$code = '<?php echo $_SERVER["PHP_SELF"];?>';
$fp = fopen("cache/1", 'w');
fwrite($fp, $code);
fclose($fp);

您甚至可以使用 PHP 函数file_put_contents(),您在问题中发布的所有代码都变为:

file_put_contents('cache/1', '<?php echo $_SERVER["PHP_SELF"];?>');

如果您需要在生成的文件中放置更大的 PHP 代码块,那么您可以使用 nowdoc 字符串语法:

$code = <<<'END_CODE'
<?php
// A lot of code here
// on multiple lines
// It is not parsed for variables and it arrives as is
// into the $code variable
$path = $_SERVER['PHP_SELF'];
echo('The path of this file is: '.$path."'n");
$newPath = dirname($path).'/'.(1+(int)basename($path));
echo('The path of next file is: '.$newPath."'n");
// That's all; there is no need for the PHP closing tag
END_CODE;
// Now, the lines 2-11 from the code above are stored verbatim in variable $code
// Put them in a file
file_put_contents('cache/1', $code);