[英]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創建了一個文件,而且我在上面,所以為什么它認為當前頁面是“ 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.