03 December 2015

关于php内核的SAPI接口。

当在命令行输入:

$ php -r "phpinfo();"

你就会在cli端看到:

phpinfo()
PHP Version => 5.3.13

System => Windows NT CBS-PC 6.1 build 7600 (Windows 7 Business Edition) AMD64
Build Date => May 14 2012 02:46:11
Compiler => MSVC9 (Visual C++ 2008)
Architecture => x64
Configure Command => cscript /nologo configure.js  "--enable-snapshot-build" "--with-pdo-oci=C:\php-sdk\php53dev\vc9\x64\deps\instantclient_10_2\sdk,shared" "--with-oci8=C:\php-sdk\php53dev\vc9\x64\deps\
instantclient_10_2\sdk,shared" "--with-oci8-11g=C:\php-sdk\php53dev\vc9\x64\deps\instantclient_11_2\sdk,shared" "--disable-debug-pack" "--disable-static-analyze"
……


通过上面的这个例子,你会看到,当你在命令行输入,shell命令后,执行了php脚本,并且打印到了cli端。那么这个shell命令和php 引擎之间一定有种接口,能将shell的参数,代码,转换成php,然后又将php的标准输入转化成shell ,打印在了终端。

这个接口就叫SAPI(Server Application Programimg Interface)。

由于php程序可以在命令行执行,也可以在web server 上执行,所以在终端上的SAPI就叫做CLI SAPI,在web server 上的SAPI 就叫做CGI SAPI。

脚本执行的开始都是以SAPI接口实现开始的。只是不同的SAPI接口实现会完成他们特定的工作。SAPI提供了一个和外部通信的接口, 对于PHP5.n,默认提供了很多种SAPI。这里主要是看看CGI SAPI的底层实现。


PHP的架构图:

haha

查看 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
};

ps : 详情请参考鸟哥的技术博客:深入理解Zend SAPIs