簡體   English   中英

PHP FastCGI簡單計數器

[英]PHP FastCGI Simple Counter

我無法理解並在FCGI模式下運行簡單的PHP腳本。 我正在學習Perl和PHP,我在下面的Perl版本的FastCGI示例中按預期工作。

Perl FastCGI計數器:

#!/usr/bin/perl

use FCGI;

$count = 0;

while (FCGI::accept() >= 0) {

    print("Content-type: text/html\r\n\r\n",
          "<title>FastCGI Hello! (Perl)</title>\n",
          "<h1>FastCGI Hello! (Perl)</h1>\n",
          "Request number ", $++count,
          " running on host <i>$ENV('SERVER_NAME')</i>");

}

在PHP中搜索類似的內容發現了關於“fastcgi_finish_request”的討論,但不知道如何在PHP中完成計數器示例,這是我嘗試過的:

<?php
header("content-type: text/html");
$counter++;
echo "Counter: $counter ";
//http://www.php.net/manual/en/intro.fpm.php
fastcgi_finish_request(); //If you remove this line, then you will see that the browser has to wait 5 seconds
sleep(5);
?>

Perl不是PHP。 這並不意味着你不能經常在兩者之間交換東西和端口代碼,但是當涉及到運行時環境時,你不能只是交換更大的差異。

FCGI已處於請求/協議級別,已在PHP運行時完全抽象化,因此您在PHP中的控制力不如使用Perl和use FCGI;

因此,您不能只是移植該代碼。

fastcgi_finish_request旁邊的內容與Perl代碼完全無關。 你必須把它弄糊塗或者通過純粹的運氣把它扔進去嘗試一下。 然而,在這個反例示例中,它並沒有真正有用。

PHP和HTTP是無狀態的。 所有數據僅與當前正在進行的請求相關。 如果需要保存狀態,可以考慮將數據存儲到cookie,session,cache或db中。

因此,這個“計數器”示例的實現對於PERL和PHP將是不同的。

您對fastcgi_finish_request使用不會帶來您期望從PERL獲得的功能。 考慮長時間運行的計算,您可以在中間輸出數據。 您可以使用fastcgi_finish_request執行此操作,然后將數據推送到瀏覽器,同時長時間運行的任務繼續運行。

開放一起發生FASTCGI + PHP。 通常連接將在PHP完成之前打開,然后FASTCGI將關閉。 除了達到PHP的exec超時(exec超時)或fastcgi超時(連接超時)。 fastcgi_finish_request處理這種情況,在PHP完成執行之前,關閉瀏覽器的fascgi連接。

PHP的簡單命中計數器示例

<?php
$hit_count = @file_get_contents('count.txt'); // read count from file
$hit_count++; // increment hit count by 1

echo $hit_count; //  display

@file_put_contents('count.txt', $hit_count); // store the new hit count
?>

老實說,這甚至不是你應該如何使用Perl。

相反,我建議使用CGI::Session來跟蹤會話信息:

#!/usr/bin/perl

use strict;
use warnings;

use CGI;
use CGI::Carp qw(fatalsToBrowser);
use CGI::Session;

my $q = CGI->new;
my $session = CGI::Session->new($q) or die CGI->Session->errstr;
print $session->header();

# Page View Count
my $count = 1 + ($session->param('count') // 0);
$session->param('count' => $count);

# HTML
print qq{<html>
<head><title>Hello! (Perl)</title></head>
<body>
<h1>Hello! (Perl)</h1>
<p>Request number $count running on host <i>$ENV{SERVER_NAME}</i></p>
</body>
</html>};

或者,如果你真的想要去准系統,你可以保留一個本地文件,如下所示: I still don't get locking. I just want to increment the number in the file. How can I do this? I still don't get locking. I just want to increment the number in the file. How can I do this?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM