仅使用PHP发送类似AJAX的发布请求

Ron*_*nen 3 php algorithm function http-post

我目前正在研究PHP中的一些自动化脚本(没有HTML!).我有两个PHP文件.一个是执行脚本,另一个是接收$ _POST数据并返回信息.问题是如何从一个PHP脚本发送POST到另一个PHP脚本,获取返回变量并继续处理第一个没有HTML表单且没有重定向的脚本.我需要在不同的条件下从第一个PHP文件到另一个PHP文件发出几次请求,并根据请求返回不同类型的数据.我有这样的事情:

<?php // action.php  (first PHP script)
/* 
    doing some stuff
*/
$data = sendPost('get_info');// send POST to getinfo.php with attribute ['get_info'] and return data from another file
$mysqli->query("INSERT INTO domains (id, name, address, email)
        VALUES('".$data['id']."', '".$data['name']."', '".$data['address']."', '".$data['email']."')") or die(mysqli_error($mysqli));
/* 
    continue doing some stuff
*/
$data2 = sendPost('what_is_the_time');// send POST to getinfo.php with attribute ['what_is_the_time'] and return time data from another file

sendPost('get_info' or 'what_is_the_time'){
//do post with desired attribute
return $data; }
?>
Run Code Online (Sandbox Code Playgroud)

我想我需要一些将使用属性调用的函数,发送post请求并根据请求返回数据.第二个PHP文件:

<?php // getinfo.php (another PHP script)
   if($_POST['get_info']){
       //do some actions 
       $data = anotherFunction();
       return $data;
   }
   if($_POST['what_is_the_time']){
       $time = time();
       return $time;
   }

   function anotherFunction(){
   //do some stuff
   return $result;
   }
?>
Run Code Online (Sandbox Code Playgroud)

先谢谢你们.

更新:好的.curl方法是获取php文件的输出.如何只返回$ data变量而不是整个输出?

Kar*_*rim 9

你应该使用curl.你的功能将是这样的:

function sendPost($data) {
    $ch = curl_init();
    // you should put here url of your getinfo.php script
    curl_setopt($ch, CURLOPT_URL, "getinfo.php");
    curl_setopt($ch,  CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $result = curl_exec ($ch); 
    curl_close ($ch); 
    return $result; 
}
Run Code Online (Sandbox Code Playgroud)

然后你应该这样称呼它:

$data = sendPost( array('get_info'=>1) );
Run Code Online (Sandbox Code Playgroud)