PHP cURL只需要发送而不是等待响应

Rez*_*eza 21 php curl

我需要一个PHP cURL配置,以便我的脚本能够发送请求并忽略API发送的答案.

curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
//curl_setopt($ch, CURLOPT_TIMEOUT_MS, 100);
$result = curl_exec($ch);
echo $result;
curl_close ($ch);
Run Code Online (Sandbox Code Playgroud)

我尝试添加:// curl_setopt($ ch,CURLOPT_RETURNTRANSFER,false); // curl_setopt($ ch,CURLOPT_TIMEOUT_MS,100);

但它没有正常工作,API网络服务器没有收到请求.

原因是我向API发送了大量请求,因此我的脚本非常慢,因为它等待每个请求.

任何帮助表示赞赏.

Kam*_*ski 15

发件人文件示例./ajax/sender.php

下面我们尝试ping php脚本而不等待回答

    $url = 'https://127.0.0.1/ajax/received.php';
    $curl = curl_init();                
    $post['test'] = 'examples daata'; // our data todo in received
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt ($curl, CURLOPT_POST, TRUE);
    curl_setopt ($curl, CURLOPT_POSTFIELDS, $post); 

    curl_setopt($curl, CURLOPT_USERAGENT, 'api');

    curl_setopt($curl, CURLOPT_TIMEOUT, 1); 
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl,  CURLOPT_RETURNTRANSFER, false);
    curl_setopt($curl, CURLOPT_FORBID_REUSE, true);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 1);
    curl_setopt($curl, CURLOPT_DNS_CACHE_TIMEOUT, 10); 

    curl_setopt($curl, CURLOPT_FRESH_CONNECT, true);

    curl_exec($curl);   

    curl_close($curl);  
Run Code Online (Sandbox Code Playgroud)

收到文件示例./ajax/received.php

fastcgi_finish_request(); $this->db->query('UPDATE new_hook_memory SET new=new+1 WHERE id=1');
Run Code Online (Sandbox Code Playgroud)

  • 你不能在代码中添加任何内容吗?这没用. (29认同)

小智 10

这两个解决方案对我来说效果很好

(当然已经过去很长时间了,但我不认为这个问题已经过时了)

使用file_get_contents

  //url of php to be called

$url = "example.php/test?id=1";

  //this will set the minimum time to wait before proceed to the next line to 1 second

$ctx = stream_context_create(['http'=> ['timeout' => 1]]);

file_get_contents($url,null,$ctx);

  //the php will read this after 1 second 
Run Code Online (Sandbox Code Playgroud)

使用卷曲

  //url of php to be called

$url = "example.php/test?id=1";

$test = curl_init();

  //this will set the minimum time to wait before proceed to the next line to 100 milliseconds

curl_setopt_array($test,[CURLOPT_URL=>$url,CURLOPT_TIMEOUT_MS=>100,CURLOPT_RETURNTRANSFER=>TRUE]);

curl_exec($test);

  //this line will be executed after 100 milliseconds

curl_close ($test); 
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,被调用的 php 必须设置ignore_user_abort(true)

在这两种情况下都不会打印结果,但要小心您设置的超时,它需要大于被调用的 php 开始产生结果所需的时间。


new*_*rld 5

如果可能,您可以在后台运行wget (使用exec