php实现模拟post请求用法实例

yipeiwu_com6年前PHP代码库

本文实例讲述了php实现模拟post请求的方法。分享给大家供大家参考。具体如下:

class Request{
 public static function post($url, $post_data = '', $timeout = 5){//curl
  $ch = curl_init(); 
  curl_setopt ($ch, CURLOPT_URL, $url);
  curl_setopt ($ch, CURLOPT_POST, 1);
  if($post_data != ''){
   curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
  }
  curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
  curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  curl_setopt($ch, CURLOPT_HEADER, false);
  $file_contents = curl_exec($ch);
  curl_close($ch);
  return $file_contents;
 } 
 public static function post2($url, $data=array()){//file_get_content
  $postdata = http_build_query(
   $data
  );   
  $opts = array('http' =>
      array(
       'method' => 'POST',
       'header' => 'Content-type: application/x-www-form-urlencoded',
       'content' => $postdata
      )
  );   
  $context = stream_context_create($opts);
  $result = file_get_contents($url, false, $context); 
  return $result;
 } 
 public static function post3($host,$path,$query,$others=''){//fsocket
  $post="POST $path HTTP/1.1\r\nHost: $host\r\n";
  $post.="Content-type: application/x-www-form-";
  $post.="urlencoded\r\n${others}";
  $post.="User-Agent: Mozilla 4.0\r\nContent-length: ";
  $post.=strlen($query)."\r\nConnection: close\r\n\r\n$query";
  $h=fsockopen($host,80);
  fwrite($h,$post);
  for($a=0,$r='';!$a;){
    $b=fread($h,8192);
    $r.=$b;
    $a=(($b=='')?1:0);
   }
  fclose($h);
  return $r;
 }
}
$url='http://******/con/Inter.php';
$data=Request::post($url,array('api'=>'tag_list'));
$data2=Request::post2($url,array('api'=>'tag_list'));
echo $data;

希望本文所述对大家的php程序设计有所帮助。

相关文章

搭建Vim为自定义的PHP开发工具的一些技巧

搭建Vim为自定义的PHP开发工具的一些技巧

虽然 vim 本质上只是一个编辑器。但只要配合一些适当的插件, vim 也能变成一个全功能的 IDE 。笔者使用 vim 已经有挺长一段时间了,经过反复的试验,配置了一个高效的 PHP...

thinkphp 验证码 的使用小结

 thinkphp中的验证码是可以直接调用的,非常方便,我们看一下 Think 文件夹下 有一个名为verify.class.php的文件    首先 我们...

PHP删除数组中特定元素的两种方法

方法一: <?php $arr1 = array(1,3, 5,7,8); $key = array_search(3, $arr1); if ($key !== fa...

基于php iconv函数的使用详解

unix下安装PHP的module,需要重新编译PHP,Windows下安装模板,只需将php.ini里的配置打开相应的dll就可,例如,需要加入gb库的支持,需要如下设置:extens...

解析php扩展php_curl.dll不加载的解决方法

方法一(已通过测试)已经内置有php_curl.dll,在ext目录下,此DLL用于支持SSL和zlib.在php.ini中找到有extension=php_curl.dll, 去掉前面...