Home > Backend Development > PHP Tutorial > Linux下C/C++代码调用PHP代码

Linux下C/C++代码调用PHP代码

WBOY
Release: 2016-06-23 13:44:04
Original
1246 people have browsed it

    Linux下C/C++代码可以通过popen系统函数调用PHP代码并通过fgets函数获取PHP代码echo输出的字符串。

//main.c	char str[1024] = {0};	char * cmd = "php /src/test/c.php 1234";	FILE * stream = NULL;	if ((stream = popen(cmd, "r")) == NULL){//通过popen执行PHP代码		return "";	}	std::string ret = "";	while((fgets(str, 1024, stream)) != NULL){//通过fgets获取PHP中echo输出的字符串		ret += str;	}	pclose(stream);	return ret;
Copy after login

其中,cmd的“1234”是传递给php文件的参数。PHP代码中,可以和普通的C语言中的main函数一样,通过argc和argv这2个参数来获取这个参数“1234”。

// /src/test/c.php<?phpinclude_once(dirname(__FILE__).'/m.php');include_once(dirname(__FILE__).'/m/SpsTable.php');if ($argc != 2){ //和C/C++的main函数一样,参数有2个,第一个是php文件名,第二个是main.c中cmd字符串中的“1234”	die();}array_shift($argv);//移除第一个参数,第一个参数是php文件名$spsFileId = (int)$argv[0];
Copy after login
    PHP代码中需要注意的是,如果被调用的PHP文件有include额外的PHP文件,最好通过dirname(__FILE__)或其他方法使用PHP文件的绝对路径,否则很容易出现找不到PHP文件的错误。




source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template