php模拟post提交数据,用处很多,可用来网站的采集,登陆等等

<?php
02 // PHP POST数据的三种方法
03 // php有三种方法可以post数据,分别为Curl、socket、file_get_contents:
04  
05  
06 /**
07  * Socket版本
08  * 使用方法:
09  * $post_string = "app=socket&version=beta";
10  * request_by_socket('facebook.cn','/restServer.php',$post_string);
11  */
12 function request_by_socket($remote_server$remote_path$post_string$port= 80, $timeout = 30)
13 {
14     $socket fsockopen($remote_server$port$errno$errstr$timeout);
15     if (!$socketdie("$errstr($errno)");
16  
17     fwrite($socket"POST $remote_path HTTP/1.0\r\n");
18     fwrite($socket"User-Agent: Socket Example\r\n");
19     fwrite($socket"HOST: $remote_server\r\n");
20     fwrite($socket"Content-type: application/x-www-form-urlencoded\r\n");
21     fwrite($socket"Content-length: " . (strlen($post_string) + 8) .'\r\n');
22     fwrite($socket"Accept:*/*\r\n");
23     fwrite($socket"\r\n");
24     fwrite($socket"mypost=$post_string\r\n");
25     fwrite($socket"\r\n");
26     $header "";
27     while ($str = trim(fgets($socket, 4096))) {
28         $header .= $str;
29     }
30     $data "";
31     while (!feof($socket)) {
32         $data .= fgets($socket, 4096);
33     }
34     return $data;
35 }
36  
37  
38  
39 /**
40  * Curl版本
41  * 使用方法:
42  $post_string "app=request&version=beta";
43  * request_by_curl('http://facebook.cn/restServer.php',$post_string);
44  */
45 function request_by_curl($remote_server$post_string)
46 {
47     $ch = curl_init();
48     curl_setopt($ch, CURLOPT_URL, $remote_server);
49     curl_setopt($ch, CURLOPT_POSTFIELDS, 'mypost=' $post_string);
50     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
51     curl_setopt($ch, CURLOPT_USERAGENT, "Jimmy's CURL Example beta");
52     $data = curl_exec($ch);
53     curl_close($ch);
54     return $data;
55 }
56  
57  
58 /**
59  * 其它版本
60  * 使用方法:
61  * $post_string = "app=request&version=beta";
62  * request_by_other('http://facebook.cn/restServer.php',$post_string);
63  */
64 function request_by_other($remote_server$post_string)
65 {
66     $context array(
67         'http' => array(
68             'method' => 'POST',
69             'header' => 'Content-type: application/x-www-form-urlencoded' .
70                         '\r\n'.'User-Agent : Jimmy\'s POST Example beta' .
71                         '\r\n'.'Content-length:' strlen($post_string) + 8,
72             'content' => 'mypost=' $post_string)
73         );
74     $stream_context = stream_context_create($context);
75     $data file_get_contents($remote_server, false, $stream_context);
76     return $data;
77 }
78  
79 ?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值