【问题标题】:Send AJAX-like post request using PHP only仅使用 PHP 发送类似 AJAX 的发布请求
【发布时间】:2025-11-23 05:50:03
【问题描述】:

我目前正在编写一些 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; }
?>

我想我需要一些使用属性调用的函数,发送发布请求并根据请求返回数据。 第二个 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 中这样做呢?
  • 我没有 html 页面,没有 javascript,没有表单,没有用户交互。只有 2 个 PHP 文件。
  • 将 file_get_contents 与上下文(或 cURL)一起使用。
  • 问题是,sendPost($attrs) 函数会是什么样子?
  • 它看起来像 php 代码

标签: php algorithm function http-post


【解决方案1】:

您应该使用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)); ??
  • 只传递一个包含所有参数的数组:$data = sendPost (array('param1'=>'val1', 'param2'=>'val2'));
  • 在你的情况下你应该写 $data = sendPost(array_merge(array('get_info'=>1), $otherParams));正常工作
  • curl 方法正在获取 php 文件的输出。如何只返回一个 $data 变量而不是整个输出?
  • 没有简单的方法可以做到这一点。您可以使用占位符将 $data 变量输出包装起来,然后使用 preg_match 或 strpos 来获取它,但这是非常糟糕的方式。
【解决方案2】:

我会给你一些示例类,在下面的示例中,你可以将其用作获取和发布调用。我希望这会对你有所帮助。!

 /*
  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;
}

}

【讨论】:

  • 虽然此代码 sn-p 可能是解决方案,但 including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
最近更新 更多