使用curl模拟post多数据到远程服务器

由于使用get方式传输的数据量太少,故而使用post,注意设置超时时间
更多POST方式可以参考http://www.oschina.net/code/snippet_127872_6370

function request_by_curl($remote_server,$post_string,$second=60){
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$remote_server);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$post_string);
    curl_setopt($ch,CURLOPT_TIMEOUT,$second); 
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2');
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

现在系统代码中经常会使用到file_get_contents这个函数同样也可以post,注意设置超时时间
参考:http://www.cnblogs.com/samson/archive/2011/08/12/2135834.html

<?php
function Post($url, $post = null,$type='POST')
{
     $context = array();
     if (is_array($post))
     {
         $opts = array(
            'http' => array(
              'timeout'=>60,
                'method'=>$type,
              'content' => http_build_query($post),
                'header' => 'Content-Type:application/x-www-form-urlencoded;',
            ),
        );
  if($type!='POST')
  {
   $url .= '?'.$opts['http']['content'];
  }
     }
     return file_get_contents($url, false, stream_context_create($opts));
}
$data = array
(
     'name' => 'test',
     'email' => 'test@gmail.com',
     'submit' => 'submit',
);
$cnt=0;
while($cnt < 3 && ($str=Post('http://localhost/test5.php', $data,'POST'))===FALSE)
{
 $cnt++;
}
var_dump($str);
?>

Related posts:

Leave a Reply

Your email address will not be published.