1

如何使用 PHP 通过同一个套接字获取和发布数据?我有这个代码:

$fp = fsockopen("ssl://ovi.rdw.nl", 443, $errno, $errstr, 30);
if(!$fp){
    echo $errstr;
}else{
$post_data = 'ctl00$cntMaincol$btnZoeken=Zoeken&ctl00$cntMaincol$txtKenteken=83FHVN';

$out = "GET /Default.aspx HTTP/1.0\r\n";
$out .= "Host: ovi.rdw.nl\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);

while(!feof($fp)){
    $data = fgets($fp);
    $view_state = getViewState($data);
    if($view_state != ""){
        echo $view_state."<br />";
        break;
    }
}

$post_data = "__VIEWSTATE={$view_state}&".$post_data;

$out = "POST /Default.aspx HTTP/1.0\r\n";
$out .= "Host: ovi.rdw.nl\r\n";
$out .= "Content-type: application/x-www-form-urlencoded\r\n";
$out .= "Content-length: " . strlen($post_data) . "\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
fwrite($fp, $post_data);
while(!feof($fp)){
    echo fgets($fp);
}
}

它得到了正确的数据,但发布它并不顺利。我想念什么?

4

3 回答 3

1

您在同一个连接中执行 GET 和 POST,这对于您已指定并通过连接重新保证的 HTTP/1.0 无效:关闭。注释掉您的获取部分,然后发布。

您可以通过 post 取回数据,因此您无需执行 get 和 post。或者,如果您确实需要执行获取和发布,请关闭套接字,然后再次为发布重新建立套接字。

于 2010-11-09T15:31:11.607 回答
0

不要忘记fflush()

于 2010-11-09T15:26:10.857 回答
0

在某些情况下,卷曲太重,无法使用 post_to_host():

//GET:
$str_rtn=post_to_host($str_url_target, array(), $arr_cookie, $str_url_referer, $ref_arr_head, 0);

//POST:
$arr_params=array('para1'=>'...', 'para2'=>'...');
$str_rtn=post_to_host($str_url_target, $arr_params, $arr_cookie, $str_url_referer, $ref_arr_head);

//POST with file:
$arr_params=array('para1'=>'...', 'FILE:para2'=>'/tmp/test.jpg', 'para3'=>'...');
$str_rtn=post_to_host($str_url_target, $arr_params, $arr_cookie, $str_url_referer, $ref_arr_head, 2);

//raw POST:
$tmp=array_search('uri', @array_flip(stream_get_meta_data($GLOBALS[mt_rand()]=tmpfile())));
$arr_params=array('para1'=>'...', 'para2'=>'...');
file_put_contents($tmp, json_encode($arr_params));
$arr_params=array($tmp);
$str_rtn=post_to_host($str_url_target, $arr_params, $arr_cookie, $str_url_referer, $ref_arr_head, 3);

//get cookie and merge cookies:
$arr_new_cookie=get_cookies_from_heads($ref_arr_head)+$arr_old_cookie;//don't change the order

//get redirect url:
$str_url_redirect=get_from_heads($ref_arr_head, 'Location');

发布到主机 php 项目位置:http ://code.google.com/p/post-to-host/

于 2012-01-05T06:53:31.107 回答