PHP SAPI架构概述
SAPI全称为Server Abstraction API,在PHP整体架构体系中占据着至关重要的地位。它充当了一个标准化接口,使得PHP能够与各类外部应用程序进行高效的数据交换。本文将不逐一列举所有PHP支持的SAPI类型,而是聚焦于最基础的CGI SAPI,以此阐明SAPI运行的基本机制。
首先,我们需要从宏观视角审视PHP的整体架构图:

图1 PHP Architecture
SAPI的核心职责是建立与外部环境的通信桥梁。在PHP5.2版本中,默认内置了多种SAPI实现,包括面向Apache的mod_php5、通用的CGI模式、针对IIS的ISAPI以及命令行下的CLI。尽管CGI模式看似简单,但它涵盖了SAPI机制的大部分核心逻辑,足以帮助读者深刻理解其工作原理。
sapi_module_struct结构体详解
定义一个新的SAPI,首要步骤是构建一个sapi_module_struct结构体。我们可以参考源码路径PHP-SRC/sapi/cgi/cgi_main.c中的具体实现:
*/
static sapi_module_struct cgi_sapi_module = {
#if PHP_FASTCGI
"cgi-fcgi", /* name */
"CGI/FastCGI", /* pretty name */
#else
"cgi", /* name */
"CGI", /* pretty name */
#endif
php_cgi_startup, /* startup */
php_module_shutdown_wrapper, /* shutdown */
NULL, /* activate */
sapi_cgi_deactivate, /* deactivate */
sapi_cgibin_ub_write, /* unbuffered write */
sapi_cgibin_flush, /* flush */
NULL, /* get uid */
sapi_cgibin_getenv, /* getenv */
php_error, /* error handler */
NULL, /* header handler */
sapi_cgi_send_headers, /* send headers handler */
NULL, /* send header handler */
sapi_cgi_read_post, /* read POST data */
sapi_cgi_read_cookies, /* read Cookies */
sapi_cgi_register_variables, /* register server variables */
sapi_cgi_log_message, /* Log message */
NULL, /* Get request time */
STANDARD_SAPI_MODULE_PROPERTIES
};
该结构体包含了一系列常量与函数指针。其中name字段用于标识SAPI名称,会在调用php_info()时显示;此外还包含初始化与清理函数,以及一系列指向Zend引擎的回调函数,用于指导引擎如何读取输入数据和输出结果。
核心函数指针与回调机制
1. php_cgi_startup:当外部应用准备调用PHP时,此函数将被触发。对于CGI模式而言,它主要执行PHP的基础初始化操作:
static int php_cgi_startup(sapi_module_struct *sapi_module)
{
if (php_module_startup(sapi_module, NULL, 0) == FAILURE) {
return FAILURE;
}
return SUCCESS;
}
2. php_module_shutdown_wrapper:这是对PHP关闭流程的一个简单封装,内部直接调用php_module_shutdown函数完成资源释放。
3. activate字段:PHP在每个请求开始时都会处理初始化和资源分配任务。从上述结构可以看出,CGI SAPI并未在此处定义特殊的初始化句柄。相比之下,mod_php的实现更为复杂,它需要在Apache的内存池中注册资源析构函数、申请空间并初始化环境变量等。
4. sapi_cgi_deactivate:这是与activate对应的清理函数。顾名思义,它负责处理收尾工作。对于CGI模式,其主要任务是刷新缓冲区,确保用户在Zend引擎关闭前能接收到所有输出数据:
static int sapi_cgi_deactivate(TSRMLS_D)
{
/* flush only when SAPI was started. The reasons are:
1. SAPI Deactivate is called from two places: module init and request shutdown
2. When the first call occurs and the request is not set up, flush fails on
FastCGI.
*/
if (SG(sapi_started)) {
sapi_cgibin_flush(SG(server_context));
}
return SUCCESS;
}
5. sapi_cgibin_ub_write:该句柄告知Zend引擎如何进行数据输出。对于mod_php,此函数提供向HTTP响应流写入数据的接口;而对于CGI,则直接将内容写入标准输出stdout:
static inline size_t sapi_cgibin_single_write(const char *str, uint str_length TSRMLS_DC)
{
#ifdef PHP_WRITE_STDOUT
long ret;
#else
size_t ret;
#endif
#if PHP_FASTCGI
if (fcgi_is_fastcgi()) {
fcgi_request *request = (fcgi_request*) SG(server_context);
long ret = fcgi_write(request, FCGI_STDOUT, str, str_length);
if (ret <= 0) {
return 0;
}
return ret;
}
#endif
#ifdef PHP_WRITE_STDOUT
ret = write(STDOUT_FILENO, str, str_length);
if (ret <= 0) return 0;
return ret;
#else
ret = fwrite(str, 1, MIN(str_length, 16384), stdout);
return ret;
#endif
}
static int sapi_cgibin_ub_write(const char *str, uint str_length TSRMLS_DC)
{
const char *ptr = str;
uint remaining = str_length;
size_t ret;
while (remaining > 0) {
ret = sapi_cgibin_single_write(ptr, remaining TSRMLS_CC);
if (!ret) {
php_handle_aborted_connection();
return str_length - remaining;
}
ptr += ret;
remaining -= ret;
}
return str_length;
}
将具体的写入逻辑剥离出来,旨在简化代码结构,以便更轻松地兼容FastCGI模式的写入方式。
6. sapi_cgibin_flush:提供给Zend引擎的缓存刷新句柄。在CGI模式下,它仅简单地调用系统级的fflush函数来强制刷新缓冲区。
7. NULL:此位置通常用于让Zend验证待执行脚本文件的状态,例如检查执行权限等。CGI SAPI未提供此项功能。
8. sapi_cgibin_getenv:为Zend提供根据名称查找环境变量的接口。在mod_php5中,当脚本调用getenv()时,会间接触发此句柄。由于CGI的运行机制与CLI相似,直接继承父级Shell的环境,因此它仅简单调用系统的getenv函数:
static char *sapi_cgibin_getenv(char *name, size_t name_len TSRMLS_DC)
{
#if PHP_FASTCGI
/* when php is started by mod_fastcgi, no regular environment
is provided to PHP. It is always sent to PHP at the start
of a request. So we have to do our own lookup to get env
vars. This could probably be faster somehow. */
if (fcgi_is_fastcgi()) {
fcgi_request *request = (fcgi_request*) SG(server_context);
return fcgi_getenv(request, name, name_len);
}
#endif
/* if cgi, or fastcgi and not found in fcgi env
check the regular environment */
return getenv(name);
}
9. php_error:错误处理函数。此处提及一个扩展话题:曾有开发者建议在PHP邮件列表中讨论将PHP的错误处理机制完全面向对象化,即改写此函数句柄,使每次发生错误时都抛出异常。而在CGI模式中,它仅调用PHP标准的错误处理函数。
10. NULL:此函数通常在调用PHP的header()函数时被触发,CGI模式未提供此句柄。
11. sapi_cgi_send_headers:当需要真正发送HTTP头信息时调用此函数,通常发生在任何输出内容发送之前:
static int sapi_cgi_send_headers(sapi_headers_struct *sapi_headers TSRMLS_DC)
{
char buf[SAPI_CGI_MAX_HEADER_LENGTH];
sapi_header_struct *h;
zend_llist_position pos;
if (SG(request_info).no_headers == 1) {
return SAPI_HEADER_SENT_SUCCESSFULLY;
}
if (cgi_nph || SG(sapi_headers).http_response_code != 200)
{
int len;
if (rfc2616_headers && SG(sapi_headers).http_status_line) {
len = snprintf(buf, SAPI_CGI_MAX_HEADER_LENGTH,
"%s\r\n", SG(sapi_headers).http_status_line);
if (len > SAPI_CGI_MAX_HEADER_LENGTH) {
len = SAPI_CGI_MAX_HEADER_LENGTH;
}
} else {
len = sprintf(buf, "Status: %d\r\n", SG(sapi_headers).http_response_code);
}
PHPWRITE_H(buf, len);
}
h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
while (h) {
/* prevent CRLFCRLF */
if (h->header_len) {
PHPWRITE_H(h->header, h->header_len);
PHPWRITE_H("\r\n", 2);
}
h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
}
PHPWRITE_H("\r\n", 2);
return SAPI_HEADER_SENT_SUCCESSFULLY;
}
12. NULL:此位置用于单独发送每一个Header,CGI模式未提供此功能。
13. sapi_cgi_read_post:该句柄定义了获取POST数据的方式。熟悉CGI编程的开发者知道,CGI是从标准输入stdin中读取POST数据的:
static int sapi_cgi_read_post(char *buffer, uint count_bytes TSRMLS_DC)
{
uint read_bytes=0, tmp_read_bytes;
#if PHP_FASTCGI
char *pos = buffer;
#endif
count_bytes = MIN(count_bytes, (uint) SG(request_info).content_length - SG(read_post_bytes));
while (read_bytes < count_bytes) {
#if PHP_FASTCGI
if (fcgi_is_fastcgi()) {
fcgi_request *request = (fcgi_request*) SG(server_context);
tmp_read_bytes = fcgi_read(request, pos, count_bytes - read_bytes);
pos += tmp_read_bytes;
} else {
tmp_read_bytes = read(0, buffer + read_bytes, count_bytes - read_bytes);
}
#else
tmp_read_bytes = read(0, buffer + read_bytes, count_bytes - read_bytes);
#endif
if (tmp_read_bytes <= 0) {
break;
}
read_bytes += tmp_read_bytes;
}
return read_bytes;
}
14. sapi_cgi_read_cookies:与上述函数类似,专门用于获取Cookie值:
static char *sapi_cgi_read_cookies(TSRMLS_D)
{
return sapi_cgibin_getenv((char *) "HTTP_COOKIE", sizeof("HTTP_COOKIE")-1 TSRMLS_CC);
}
15. sapi_cgi_register_variables:此函数提供了向$_SERVER变量添加自定义信息的接口。对于CGI模式,它注册了PHP_SELF变量,使得脚本可以通过$_SERVER['PHP_SELF']访问当前请求的资源路径:
本次请求的URI地址。
static void sapi_cgi_register_variables(zval *track_vars_array TSRMLS_DC)
{
/* In CGI mode, we consider the environment to be a part of the server
* variables
*/
php_import_environment_variables(track_vars_array TSRMLS_CC);
/* Build the special-case PHP_SELF variable for the CGI version */
php_register_variable("PHP_SELF", (SG(request_info).request_uri ? SG(request_info).request_uri : ""), track_vars_array TSRMLS_CC);
}
16. sapi_cgi_log_message:用于输出错误日志。在CGI模式下,它仅将日志信息简单输出到标准错误流stderr:
static void sapi_cgi_log_message(char *message)
{
#if PHP_FASTCGI
if (fcgi_is_fastcgi() && fcgi_logging) {
fcgi_request *request;
TSRMLS_FETCH();
request = (fcgi_request*) SG(server_context);
if (request) {
int len = strlen(message);
char *buf = malloc(len+2);
memcpy(buf, message, len);
memcpy(buf + len, "\n", sizeof("\n"));
fcgi_write(request, FCGI_STDERR, buf, len+1);
free(buf);
} else {
fprintf(stderr, "%s\n", message);
}
/* ignore return code */
} else
#endif /* PHP_FASTCGI */
fprintf(stderr, "%s\n", message);
}
通过对CGI SAPI的详细分析,我们已经清楚了SAPI的实现原理。理解了CGI之后,读者也可以举一反三,推导出mod_php、embed等其他SAPI的实现机制。
希望本文对SAPI机制的详细拆解能对大家有所帮助。