您的位置:首页 > 运维架构 > 网站架构

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

2013-07-26 16:42 761 查看
<?php
02
//
PHPPOST数据的三种方法
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
(!
$socket
)
die
(
"$errstr($errno)"
);
16
17
fwrite(
$socket
,
"POST
$remote_pathHTTP/1.0\r\n"
);
18
fwrite(
$socket
,
"User-Agent:
SocketExample\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
CURLExamplebeta"
);
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\'sPOSTExamplebeta'
.
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
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PHP post 模拟登录