使用仅PHP发送类AJAX的POST请求

4

我目前在使用 PHP 编写自动化脚本(无HTML!)。

我有两个 PHP 文件。其中一个执行脚本,另一个接收 $_POST 数据并返回信息。

问题是如何从一个 PHP 脚本发送 POST 请求到另一个 PHP 脚本,获取返回的变量,而不使用 HTML 表单或重定向,并且继续在第一个脚本中进行工作。

我需要在第一个 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; }
?>

我认为我需要一个函数,该函数将使用属性调用,并发送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;
   }
?>

提前感谢你们。

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


你可以从 PHP 向其他内容发送 HTTP 请求,并操纵结果或不操纵,但既然有 AJAX,为什么不用 AJAX 呢? - Gntem
我没有HTML页面,也没有JavaScript、表单或用户交互。只有两个PHP文件。 - Ronen
使用带有上下文(或cURL)的file_get_contents。 - Salman A
it will look like php code - Gntem
可能是重复的问题:如何使用file_get_contents在PHP中发布数据? - Salman A
显示剩余3条评论
2个回答

10
你应该使用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; 
}

然后你应该这样调用它:
$data = sendPost( array('get_info'=>1) );

如果我需要传递几个参数,那么代码应该是: $data = sendPost(array('get_info'=>1, $otherParams)); ?? - Ronen
只需传递一个包含所有参数的数组:$data = sendPost( array('param1'=>'val1', 'param2'=>'val2') ); - Karim
在你的情况下,你应该写成 $data = sendPost( array_merge( array('get_info'=>1), $otherParams) ); 才能正确运行。 - Karim
curl方法正在获取php文件的输出。如何仅返回$data变量而不是整个输出? - Ronen
没有简单的方法可以做到。你可以用占位符包装$data变量输出,然后使用preg_match或strpos来获取它,但这是非常糟糕的方式。 - Karim

1

我将给你一些示例类,下面的示例中你可以使用它作为get和post调用。希望这能帮助到你!

 /*
  for your reference . Please provide argument like this,
  $requestBody = array(
                    'action' => $_POST['action'],
                    'method'=> $_POST['method'],
                    'amount'=> $_POST['amount'],
                    'description'=> $_POST['description']
                   );
 $http = "http://localhost/test-folder/source/signup.php";
 $resp = Curl::postAuth($http,$requestBody);
 */   

class Curl {
// without header
public static function post($http,$requestBody){
    
     $curl = curl_init();
        // Set some options - we are passing in a useragent too here
        curl_setopt_array($curl, array(
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => $http ,
            CURLOPT_USERAGENT => 'From Front End',
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => $requestBody
        ));           
        // Send the request & save response to $resp
        $resp = curl_exec($curl);
        // Close request to clear up some resources           
        curl_close($curl);
        return $resp;
}
// with authorization header
public static function postAuth($http,$requestBody,$token){
    if(!isset($token)){
        $resposne = new stdClass();
        $resposne->code = 400;
        $resposne-> message = "auth not found";
       return json_encode($resposne);
    }
     $curl = curl_init();
      $headers = array(                
            'auth-token: '.$token,
        );
        // Set some options - we are passing in a useragent too here
        curl_setopt_array($curl, array(
            CURLOPT_HTTPHEADER  => $headers ,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => $http ,
            CURLOPT_USERAGENT => 'From Front End',
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => $requestBody
        ));
        
       
        // Send the request & save response to $resp
        $resp = curl_exec($curl);
        // Close request to clear up some resources           
        curl_close($curl);
        return $resp;
}

}


2
虽然这段代码片段可能是解决方案,但包括解释真的有助于提高您的帖子质量。请记住,您正在回答未来读者的问题,而这些人可能不知道您的代码建议的原因。 - Matheus Cuba

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接