php中发送异步请求,关于http:如何在PHP中发出异步GET请求?

这篇博客探讨了如何使用PHP进行简单的GET请求,包括通过fsockopen、cURL和其他方法。还讨论了异步请求的可能性以及如何在不等待响应的情况下执行请求。文章提到了同步和异步请求之间的区别,并提供了适用于不同场景的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我希望对其他服务器上的另一个脚本进行简单的GET请求。 我该怎么做呢?

在一种情况下,我只需要请求一个外部脚本,而无需任何输出。

make_request('http://www.externalsite.com/script1.php?variable=45'); //example usage

在第二种情况下,我需要获取文本输出。

$output = make_request('http://www.externalsite.com/script2.php?variable=45');

echo $output; //string output

老实说,我不想弄乱CURL,因为这实际上不是CURL的工作。 我也不想使用http_get,因为我没有PECL扩展名。

fsockopen可以工作吗? 如果是这样,该如何在不读取文件内容的情况下执行此操作? 有没有其他办法?

谢谢大家

更新资料

我应该补充,在第一种情况下,我不想等待脚本返回任何内容。 据我了解,file_get_contents()将等待页面完全加载等?

@威廉姆斯:是的,大多数问题都可以看作是它们的重复。 8-)我认为您发布了错误的链接...

重复:stackoverflow.com/questions/959063/

我的意思是发布链接musicfreak,将我的标签混在一起;-)

@Richie:大多数问题吗? ;)

请参阅我有问题的更新。

我重新命名了该问题,以使其与其他问题区分开,因为您似乎想发出一个请求,而不在乎使用响应(因此它可能在脚本其余部分运行时发生)。如果我误会了,将其还原!

@Abs看到我的答案更新了吗?它可能有效...虽然我还没有实际尝试过...

这是一篇有用的文章,讨论了3个选项:segment.com/blog/how-to-make-async-requests-in-php

为什么不仅仅使用exec来调用另一个php脚本并在那个file_get_content中使用?

我用Gearman处理这种情况-HTTP请求非常快速/最小,因为服务器只是将作业放在队列中进行异步处理并完成请求。

file_get_contents将做您想要的

$output = file_get_contents('http://www.example.com/');

echo $output;

编辑:一种触发GET请求并立即返回的方法。

引用自http://petewarden.typepad.com/searchbrowser/2008/06/how-to-post-an.html

function curl_post_async($url, $params)

{

foreach ($params as $key => &$val) {

if (is_array($val)) $val = implode(',', $val);

$post_params[] = $key.'='.urlencode($val);

}

$post_string = implode('&', $post_params);

$parts=parse_url($url);

$fp = fsockopen($parts['host'],

isset($parts['port'])?$parts['port']:80,

$errno, $errstr, 30);

$out ="POST".$parts['path']." HTTP/1.1

";

$out.="Host:".$parts['host']."

";

$out.="Content-Type: application/x-www-form-urlencoded

";

$out.="Content-Length:".strlen($post_string)."

";

$out.="Connection: Close

";

if (isset($post_string)) $out.= $post_string;

fwrite($fp, $out);

fclose($fp);

}

这是打开一个套接字,触发一个get请求,然后立即关闭该套接字并返回。

curl_post_async发送POST请求,而不是GET。

是的,您为什么要POST请求?实际上,我认为HEAD请求最有意义。

是的,很好。使该curl_get_async并使用GET替换POST。我还认为HEAD请求会更有意义,但这会更快一点吗?我认为?

仅将POST更改为GET并不能解决问题。因此,我将其保留为POST,最后立即返回了我的脚本! :)

@Abs:我的以下回答显示了如何使用GET而不是POST来获得相同的结果。

这是一个伟大的开始。我能够清理它并使其变得更快,更灵活! gist.github.com/1898009

我说这个函数的名称不正确是对的吗?它确实与curl库没有任何关系。它的fsock_post_async()更像它

这不是异步的!特别是如果另一端的服务器关闭,则这段代码将挂起30秒(fsockopen中的第5个参数)。同样,fwrite将花费其甜蜜的时间来执行(您可以用stream_set_timeout($ fp,$ my_timeout)进行限制。最好的办法是将fsockopen的低超时设置为0.1(100ms),将$ my_timeout设置为100ms但是,您冒风险,即请求超时。

需要注意的一件事是,如果所请求的URL被重写(即服务器使用mod_rewrite),则此方法将不起作用。您需要使用类似curl的方法。

这与异步无关。这就是同步的方式...异步意味着在此任务完成时执行其他任务。它并行执行。

这既不是异步的,也不是使用curl,您怎么敢称它为curl_post_async甚至获得投票...

真正的异步可以通过多线程来实现:stackoverflow.com/questions/70855/

exec("curl $url > devnull 2>&1 &");是最快的解决方案之一(感谢@Matt Huggins)。它比curl_post_async()函数(14.8s)快得多(100次迭代为1.9s)。自从其完善的cURL以来,它没有相同的超时/ URL重写/限制。和它的单线...

这个答案确实过时了,不支持HTTPS。

这是使Marquis的答案同时适用于POST和GET请求的方法:

// $type must equal 'GET' or 'POST'

function curl_request_async($url, $params, $type='POST')

{

foreach ($params as $key => &$val) {

if (is_array($val)) $val = implode(',', $val);

$post_params[] = $key.'='.urlencode($val);

}

$post_string = implode('&', $post_params);

$parts=parse_url($url);

$fp = fsockopen($parts['host'],

isset($parts['port'])?$parts['port']:80,

$errno, $errstr, 30);

// Data goes in the path for a GET request

if('GET' == $type) $parts['path'] .= '?'.$post_string;

$out ="$type".$parts['path']." HTTP/1.1

";

$out.="Host:".$parts['host']."

";

$out.="Content-Type: application/x-www-form-urlencoded

";

$out.="Content-Length:".strlen($post_string)."

";

$out.="Connection: Close

";

// Data goes in the request body for a POST request

if ('POST' == $type && isset($post_string)) $out.= $post_string;

fwrite($fp, $out);

fclose($fp);

}

这是一个方便的代码段,我在这里和那里一直在使用它,但是现在我发现我需要做同样的事情,但是要使用SSL站点。除了HTTP / 1.1类型和端口外,我还需要更改什么吗?

在回答有关对此使用SSL的问题时,您可以通过将端口更改为443并将ssl://附加到fsockopen中的端口名称来使其成为SSL:$ fp = fsockopen(" ssl://"。$ parts [host] ,

您能否更具体地说明如何调用此函数。

"除了HTTP / 1.1类型和端口之外,我还需要更改什么吗?" -是的,您应该使用主机名ssl:hostname而不是hostname来调用fsockopen()。

这不是异步的!特别是如果另一端的服务器关闭,则这段代码将挂起30秒(fsockopen中的第5个参数)。同样,fwrite将花费其甜蜜的时间来执行(您可以用stream_set_timeout($ fp,$ my_timeout)进行限制。最好的办法是将fsockopen的低超时设置为0.1(100ms),将$ my_timeout设置为100ms但是,您冒风险,即请求超时。

我试过了,但是仅当我在调试器PHP Storm中逐步浏览代码时才起作用:/是否有可能先取消对服务器的原始请求,然后再将其发布到另一个服务器?

不应为GET设置Content-Length。也许在某些情况下不会导致错误,但是在我的情况下,导致请求未被称为php脚本的请求处理。

关于您的更新,关于不想等待整个页面加载-我认为您正在寻找HTTP HEAD请求。

get_headers应该这样做-我认为它只请求标头,因此不会发送完整的页面内容。

" PHP / Curl:HEAD请求在某些站点上花费很长时间"描述了如何使用PHP / Curl进行HEAD请求

如果您想触发请求,而又不想完全搁置脚本,则有几种方法,它们的复杂程度各不相同。

将HTTP请求作为后台进程执行,php执行后台进程-基本上,您将执行类似"wget -O /dev/null $carefully_escaped_url"的操作-这将是特定于平台的,并且在转义命令参数时必须非常小心

在后台执行PHP脚本-与UNIX处理方法基本相同,但是执行PHP脚本而不是Shell命令

使用数据库(或类似beantalkd之类的东西,可能会导致过大杀伤力)来创建"工作队列"。您将URL添加到队列中,并且后台进程或cron-job会定期检查新任务并对该URL执行请求

+1为我从未想过的各种有趣选项

"我认为它只请求标题"-也许,但是没有什么可以阻止文档发送完整的响应正文以响应HEAD请求。我认为这种方法将在内部使用fsock并强制其等待(并读取)完整响应。

我向您推荐经过良好测试的PHP库:curl-easy

$request = new cURL

equest('http://www.externalsite.com/script2.php?variable=45');

$request->getOptions()

->set(CURLOPT_TIMEOUT, 5)

->set(CURLOPT_RETURNTRANSFER, true);

// add callback when the request will be completed

$request->addListener('complete', function (cURL\Event $event) {

$response = $event->response;

$content = $response->getContent();

echo $content;

});

while ($request->socketPerform()) {

// do anything else when the request is processed

}

Guzzle PHP库还支持执行并发和异步请求。

Guzzle声称它有支持,但是测试它的postAsync方法看起来像它同步进行150 ms,然后异步进行2 ms。我花了一个多小时试图修复它,但没有成功-不会推荐它。

你不知道虽然PHP提供了许多调用URL的方法,但它并没有提供对每个请求/执行周期进行任何类型的异步/线程处理的现成支持。发送对URL(或SQL语句等)的请求的任何方法都将等待某种响应。您需要在本地计算机上运行某种辅助系统来实现此目标(谷歌搜索" php作业队列")

这里有一个骇客:stackoverflow.com/questions/124462/asynchronous-php-calls(克里斯蒂安·戴文(Christian Davn)的回答),但我同意队列是正确的方法。

我认为2009年的答案现在已经过时。 Guzzle PHP库现在支持执行并发和异步请求。

function make_request($url, $waitResult=true){

$cmi = curl_multi_init();

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

curl_multi_add_handle($cmi, $curl);

$running = null;

do {

curl_multi_exec($cmi, $running);

sleep(.1);

if(!$waitResult)

break;

} while ($running > 0);

curl_multi_remove_handle($cmi, $curl);

if($waitResult){

$curlInfos = curl_getinfo($curl);

if((int) $curlInfos['http_code'] == 200){

curl_multi_close($cmi);

return curl_multi_getcontent($curl);

}

}

curl_multi_close($cmi);

}

您可以使它返回一个对象,让您调用getstatus()或waitSend()或waitResult()。这样,调用者可以通过循环调用以检查是否有结果,从而获得完全异步的行为,如果没有,则继续执行其他正在运行的任务。嗯,现在我想将Task从.net移植到php…

有趣的问题。我猜您只是想在另一台服务器上触发某些过程或动作,但不在乎结果是什么,并希望脚本继续执行。 cURL中可能有些东西可以使这种情况发生,但是如果cURL无法执行,您可能要考虑使用exec()在执行调用的服务器上运行另一个脚本。 (通常人们希望脚本调用的结果,因此我不确定PHP是否能够触发该过程。)使用exec(),您可以运行wget或什至另一个使用< x4>。

如果您使用的是Linux环境,则可以使用PHP的exec命令来调用linux curl。这是一个示例代码,它将发出一个异步HTTP帖子。

function _async_http_post($url, $json_string) {

$run ="curl -X POST -H 'Content-Type: application/json'";

$run.=" -d '" .$json_string."'" ."'" . $url ."'";

$run.="> /dev/null 2>&1 &";

exec($run, $output, $exit);

return $exit == 0;

}

此代码不需要任何额外的PHP库,并且可以在不到10毫秒的时间内完成http发布。

这是一个非常糟糕的主意:高管失败很多:想象一下6/200客户将不会收到付费预订的电子邮件确认...

就我而言,这对我来说很有效,因为我只需要ping即可在另一台服务器上启动另一个脚本。我只是这样使用它:_async_http_post($ url,);这正在OVH互斥服务器上工作……太好了。

让我告诉你我的方式:)

需要在服务器上安装nodejs

(我的服务器发送1000 https get请求仅需2秒)

url.php:

$urls = array_fill(0, 100, 'http://google.com/blank.html');

function execinbackground($cmd) {

if (substr(php_uname(), 0, 7) =="Windows"){

pclose(popen("start /B". $cmd,"r"));

}

else {

exec($cmd ."> /dev/null &");

}

}

fwite(fopen("urls.txt","w"),implode("

",$urls);

execinbackground("nodejs urlscript.js urls.txt");

// { do your work while get requests being executed.. }

?>

urlscript.js>

var https = require('https');

var url = require('url');

var http = require('http');

var fs = require('fs');

var dosya = process.argv[2];

var logdosya = 'log.txt';

var count=0;

http.globalAgent.maxSockets = 300;

https.globalAgent.maxSockets = 300;

setTimeout(timeout,100000); // maximum execution time (in ms)

function trim(string) {

return string.replace(/^\s*|\s*$/g, '')

}

fs.readFile(process.argv[2], 'utf8', function (err, data) {

if (err) {

throw err;

}

parcala(data);

});

function parcala(data) {

var data = data.split("

");

count=''+data.length+'-'+data[1];

data.forEach(function (d) {

req(trim(d));

});

/*

fs.unlink(dosya, function d() {

console.log(' file deleted', dosya);

});

*/

}

function req(link) {

var linkinfo = url.parse(link);

if (linkinfo.protocol == 'https:') {

var options = {

host: linkinfo.host,

port: 443,

path: linkinfo.path,

method: 'GET'

};

https.get(options, function(res) {res.on('data', function(d) {});}).on('error', function(e) {console.error(e);});

} else {

var options = {

host: linkinfo.host,

port: 80,

path: linkinfo.path,

method: 'GET'

};

http.get(options, function(res) {res.on('data', function(d) {});}).on('error', function(e) {console.error(e);});

}

}

process.on('exit', onExit);

function onExit() {

log();

}

function timeout()

{

console.log("i am too far gone");process.exit();

}

function log()

{

var fd = fs.openSync(logdosya, 'a+');

fs.writeSync(fd, dosya + '-'+count+'

');

fs.closeSync(fd);

}

这不是纯PHP解决方案。

对我来说,出现异步GET请求的问题是因为我遇到了这样的情况:我需要执行数百个请求,获取和处理每个请求的结果数据,并且每个请求花费大量的毫秒执行时间,导致几分钟(!)用简单的file_get_contents执行。

在这种情况下,对于函数http://php.net/manual/en/function.curl-multi-init.php上php.net的w_haigh注释非常有用。

因此,这是我同时进行大量请求的升级和清理版本。

就我而言,这等效于"异步"方式。可能对某人有帮助!

// Build the multi-curl handle, adding both $ch

$mh = curl_multi_init();

// Build the individual requests, but do not execute them

$chs = [];

$chs['ID0001'] = curl_init('http://webservice.example.com/?method=say&word=Hello');

$chs['ID0002'] = curl_init('http://webservice.example.com/?method=say&word=World');

// $chs[] = ...

foreach ($chs as $ch) {

curl_setopt_array($ch, [

CURLOPT_RETURNTRANSFER => true,  // Return requested content as string

CURLOPT_HEADER => false,         // Don't save returned headers to result

CURLOPT_CONNECTTIMEOUT => 10,    // Max seconds wait for connect

CURLOPT_TIMEOUT => 20,           // Max seconds on all of request

CURLOPT_USERAGENT => 'Robot YetAnotherRobo 1.0',

]);

// Well, with a little more of code you can use POST queries too

// Also, useful options above can be  CURLOPT_SSL_VERIFYHOST => 0

// and  CURLOPT_SSL_VERIFYPEER => false ...

// Add every $ch to the multi-curl handle

curl_multi_add_handle($mh, $ch);

}

// Execute all of queries simultaneously, and continue when ALL OF THEM are complete

$running = null;

do {

curl_multi_exec($mh, $running);

} while ($running);

// Close the handles

foreach ($chs as $ch) {

curl_multi_remove_handle($mh, $ch);

}

curl_multi_close($mh);

// All of our requests are done, we can now access the results

// With a help of ids we can understand what response was given

// on every concrete our request

$responses = [];

foreach ($chs as $id => $ch) {

$responses[$id] = curl_multi_getcontent($ch);

curl_close($ch);

}

unset($chs); // Finita, no more need any curls :-)

print_r($responses); // output results

很容易将其重写以处理POST或其他类型的HTTP(S)请求或它们的任何组合。和Cookie支持,重定向,http-auth等。

哦..我看到这个问题是在2009年创建的,我在2016年写下了我的答案:)但是我们很多人google php都变得异步了,来到了这里。

是的,我在谷歌搜索时也来到了这里。一些编码人员可能还想研究Guzzle PHP库,该库支持执行并发和异步请求。

您最好考虑使用消息队列而不是建议的方法。

我敢肯定这将是一个更好的解决方案,尽管它比发送请求所需要的工作还要多。

似乎没有人提到Guzzle,这是一个PHP HTTP客户端,可以轻松发送HTTP请求。无论是否使用Curl,它都可以工作。它可以发送同步和异步请求。

$client = new GuzzleHttp\Client();

$promise = $client->requestAsync('GET', 'http://httpbin.org/get');

$promise->then(

function (ResponseInterface $res) {

echo $res->getStatusCode() ."

";

},

function (RequestException $e) {

echo $e->getMessage() ."

";

echo $e->getRequest()->getMethod();

}

);

是的,该主题中的许多答案都已经很老了,但是Guzzle绝对是Ive在2018年遇到的最佳选择,谢谢发布。

这是用于执行简单GET请求的已接受答案的改编。

需要注意的一点是,如果服务器执行任何URL重写,则此操作将无效。您需要使用功能更全的http客户端。

/**

* Performs an async get request (doesn't wait for response)

* Note: One limitation of this approach is it will not work if server does any URL rewriting

*/

function async_get($url)

{

$parts=parse_url($url);

$fp = fsockopen($parts['host'],

isset($parts['port'])?$parts['port']:80,

$errno, $errstr, 30);

$out ="GET".$parts['path']." HTTP/1.1

";

$out.="Host:".$parts['host']."

";

$out.="Connection: Close

";

fwrite($fp, $out);

fclose($fp);

}

我发现这个有趣的链接可以进行异步处理(获取请求)。

阿卡帕奇

此外,您可以通过使用消息队列(例如beantalkd)来进行异步处理。

尝试:

//Your Code here

$pid = pcntl_fork();

if ($pid == -1) {

die('could not fork');

}

else if ($pid)

{

echo("Bye")

}

else

{

//Do Post Processing

}

这将无法用作apache模块,您需要使用CGI。

对上面发布的脚本进行了一些更正。以下为我工作

function curl_request_async($url, $params, $type='GET')

{

$post_params = array();

foreach ($params as $key => &$val) {

if (is_array($val)) $val = implode(',', $val);

$post_params[] = $key.'='.urlencode($val);

}

$post_string = implode('&', $post_params);

$parts=parse_url($url);

echo print_r($parts, TRUE);

$fp = fsockopen($parts['host'],

(isset($parts['scheme']) && $parts['scheme'] == 'https')? 443 : 80,

$errno, $errstr, 30);

$out ="$type".$parts['path'] . (isset($parts['query']) ? '?'.$parts['query'] : '') ." HTTP/1.1

";

$out.="Host:".$parts['host']."

";

$out.="Content-Type: application/x-www-form-urlencoded

";

$out.="Content-Length:".strlen($post_string)."

";

$out.="Connection: Close

";

// Data goes in the request body for a POST request

if ('POST' == $type && isset($post_string)) $out.= $post_string;

fwrite($fp, $out);

fclose($fp);

}

我有一个问题,其中fwrite返回一个正数的字节,但脚本端点未调用(未记录)..仅当我使用时它才起作用:while(!feof($ fp)){fgets($ fp ,128); }

建议:格式化FRAMESET HTML页面,其中包含9帧。每个框架都会获取myapp.php页面的不同"实例"。 Web服务器上将并行运行9个不同的线程。

基于此线程,我将其用于我的codeigniter项目。它工作正常。您可以在后台处理任何功能。

接受异步调用的控制器。

class Daemon extends CI_Controller

{

// Remember to disable CI's csrf-checks for this controller

function index( )

{

ignore_user_abort( 1 );

try

{

if ( strcmp( $_SERVER['REMOTE_ADDR'], $_SERVER['SERVER_ADDR'] ) != 0 && !in_array( $_SERVER['REMOTE_ADDR'], $this->config->item( 'proxy_ips' ) ) )

{

log_message("error","Daemon called from untrusted IP-address:" . $_SERVER['REMOTE_ADDR'] );

show_404( '/daemon' );

return;

}

$this->load->library( 'encrypt' );

$params = unserialize( urldecode( $this->encrypt->decode( $_POST['data'] ) ) );

unset( $_POST );

$model = array_shift( $params );

$method = array_shift( $params );

$this->load->model( $model );

if ( call_user_func_array( array( $this->$model, $method ), $params ) === FALSE )

{

log_message("error","Daemon could not call:" . $model ."::" . $method ."()" );

}

}

catch(Exception $e)

{

log_message("error","Daemon has error:" . $e->getMessage( ) . $e->getFile( ) . $e->getLine( ) );

}

}

}

还有一个执行异步调用的库

class Daemon

{

public function execute_background( /* model, method, params */ )

{

$ci = &get_instance( );

// The callback URL (its ourselves)

$parts = parse_url( $ci->config->item( 'base_url' ) ."/daemon" );

if ( strcmp( $parts['scheme'], 'https' ) == 0 )

{

$port = 443;

$host ="ssl://" . $parts['host'];

}

else

{

$port = 80;

$host = $parts['host'];

}

if ( ( $fp = fsockopen( $host, isset( $parts['port'] ) ? $parts['port'] : $port, $errno, $errstr, 30 ) ) === FALSE )

{

throw new Exception("Internal server error: background process could not be started" );

}

$ci->load->library( 'encrypt' );

$post_string ="data=" . urlencode( $ci->encrypt->encode( serialize( func_get_args( ) ) ) );

$out ="POST" . $parts['path'] ." HTTP/1.1

";

$out .="Host:" . $host ."

";

$out .="Content-Type: application/x-www-form-urlencoded

";

$out .="Content-Length:" . strlen( $post_string ) ."

";

$out .="Connection: Close

";

$out .= $post_string;

fwrite( $fp, $out );

fclose( $fp );

}

}

可以调用此方法来处理"背景"中的任何model :: method()。它使用可变参数。

$this->load->library('daemon');

$this->daemon->execute_background( 'model', 'method', $arg1, $arg2, ... );

对于PHP5.5 +,mpyw / co是最终的解决方案。它的工作方式就像JavaScript中的tj / co。

假设您要下载指定的多个GitHub用户的头像。每个用户都需要执行以下步骤。

获取http://github.com/mpyw的内容(获取HTML)

查找并请求...(获取图像)

---:等待我的回复

...:在并行流中等待其他响应

许多基于curl_multi的著名脚本已经为我们提供了以下流程。

/-----------GET HTML\  /--GET IMAGE.........\

/                     \/                      \

[Start] GET HTML..............----------------GET IMAGE [Finish]

\                     /\                      /

\-----GET HTML....../  \-----GET IMAGE....../

但是,这不够有效。您是否要减少无用的等待时间...?

/-----------GET HTML--GET IMAGE\

/                                \

[Start] GET HTML----------------GET IMAGE [Finish]

\                                /

\-----GET HTML-----GET IMAGE.../

是的,使用mpyw / co非常容易。有关更多详细信息,请访问存储库页面。

当我执行POST到任何页面的特定URL时,这是我自己的PHP函数。

示例:*我的功能的使用...

parse_str("email=myemail@ehehehahaha.com&subject=this is just a test");

$_POST['email']=$email;

$_POST['subject']=$subject;

echo HTTP_Post("http://example.com/mail.php",$_POST);***

exit;

?>

/*********HTTP POST using FSOCKOPEN **************/

// by ArbZ

function HTTP_Post($URL,$data, $referrer="") {

// parsing the given URL

$URL_Info=parse_url($URL);

// Building referrer

if($referrer=="") // if not given use this script as referrer

$referrer=$_SERVER["SCRIPT_URI"];

// making string from $data

foreach($data as $key=>$value)

$values[]="$key=".urlencode($value);

$data_string=implode("&",$values);

// Find out which port is needed - if not given use standard (=80)

if(!isset($URL_Info["port"]))

$URL_Info["port"]=80;

// building POST-request: HTTP_HEADERs

$request.="POST".$URL_Info["path"]." HTTP/1.1

";

$request.="Host:".$URL_Info["host"]."

";

$request.="Referer: $referer

";

$request.="Content-type: application/x-www-form-urlencoded

";

$request.="Content-length:".strlen($data_string)."

";

$request.="Connection: close

";

$request.="

";

$request.=$data_string."

";

$fp = fsockopen($URL_Info["host"],$URL_Info["port"]);

fputs($fp, $request);

while(!feof($fp)) {

$result .= fgets($fp, 128);

}

fclose($fp); //$eco = nl2br();

function getTextBetweenTags($string, $tagname) {

$pattern ="/(.*)/";

preg_match($pattern, $string, $matches);

return $matches[1]; }

//STORE THE FETCHED CONTENTS to a VARIABLE, because its way better and fast...

$str = $result;

$txt = getTextBetweenTags($str,"span"); $eco = $txt;  $result = explode("&",$result);

return $result[1];

".trim($_GET['em'])."

";

}

pre>

code> pre>

试试这个代码。

$chu = curl_init();

curl_setopt($chu, CURLOPT_URL, 'http://www.myapp.com/test.php?someprm=xyz');

curl_setopt($chu, CURLOPT_FRESH_CONNECT, true);

curl_setopt($chu, CURLOPT_TIMEOUT, 1);

curl_exec($chu);

curl_close($chu);

请不要忘记启用CURL php扩展。

这不是异步的。

您可以设置CURLOPT_TIMEOUT_MS例如100毫秒(而不是CURLOPT_TIMEOUT)以秒为单位,而CURLOPT_TIMEOUT以秒为单位,且最小值为1秒-以便更快地执行。

这对我来说很好用,可惜您无法从请求中获取响应:

header("http://mahwebsite.net/myapp.php?var=dsafs");

?>

它的工作速度非常快,不需要原始的tcp套接字:)

你检查这个吗?它不起作用

此函数向响应中添加标头...它不发送标头请求。 php.net/manual/bg/function.header.php

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值