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程序设计有所帮助。

相关文章

深入理解ob_flush和flush的区别(ob_flush()与flush()使用方法)

有关php的ob_flush()与flush()使用方法 注意:ob_flush()和flush()这两个函数一般要一起使用,顺序是先ob_flush(),然后flush(),它们的作用...

PHP常用函数小技巧

1. 返回文件扩展名 function getformat($file) { $ext=strrchr($file,"."); $format=strtolower($ext); ret...

解析php中用PHPMailer来发送邮件的示例(126.com的例子)

<?phprequire_once('../class.phpmailer.php');$mail= new PHPMailer();$body= "我终于发送邮件成功了!呵呵!g...

PHP数学运算与数据处理实例分析

本文实例讲述了PHP数学运算与数据处理方法。分享给大家供大家参考,具体如下: 一.数值数据类型 PHP中,数字或数值数据以及数学函数的使用很简单。基本来说,要处理两种数据类型:浮点数和...

php可应用于面包屑导航的递归寻找家谱树实现方法

本文实例讲述了php可应用于面包屑导航的递归寻找家谱树实现方法。分享给大家供大家参考。具体实现方法如下: <?php echo "<pre>"; $area...