标题: PHP Socket编程 之 fsockopen异步请求执行https(ssl)站点方法分享 [打印本页]
作者: xiexie 时间: 2022-11-25 18:00 标题: PHP Socket编程 之 fsockopen异步请求执行https(ssl)站点方法分享
function
request_asynchronous(
$path
,
$method
=
"POST"
,
$postData
=
array
(),
$url
=
''
){
if
(
empty
(
$path
)){
return
false;
}
if
(
$url
) {
$matches
=
parse_url
(
$url
);
$host
=
$matches
[
'host'
];
if
(
$matches
[
'scheme'
] ==
'https'
) {
$transports
=
'ssl://'
; //如使用HTTPS则使用SSL协议
$port
= !
empty
(
$matches
[
'port'
]) ?
$matches
[
'port'
] : 443;
}
else
{
$transports
=
'tcp://'
; //如没有使用HTTPS则使用tcp协议
$port
= !
empty
(
$matches
[
'port'
]) ?
$matches
[
'port'
] : 80;
}
}
else
{
$port
= 443;
$transports
=
'ssl://'
;
$host
=
$_SERVER
[
'HTTP_HOST'
];
}
$errNo
= 0;
$errStr
=
''
;
$timeout
= 60;
$fp
=
''
;
if
(function_exists(
'fsockopen'
)) {
$fp
= @
fsockopen
((
$transports
.
$host
),
$port
,
$errno
,
$errStr
,
$timeout
);
}
elseif
(function_exists(
'pfsockopen'
)) {
$fp
= @pfsockopen(
$transports
.
$host
,
$port
,
$errNo
,
$errStr
,
$timeout
);
}
elseif
(function_exists(
'stream_socket_client'
)) {
$fp
= @stream_socket_client(
$transports
.
$host
.
':'
.
$port
,
$errNo
,
$errStr
,
$timeout
);
}
if
(!
$fp
) {
return
false;
}
stream_set_blocking(
$fp
, 0);
stream_set_timeout(
$fp
, 3);
$date
= [];
if
(
$postData
) {
foreach
(
$postData
as
$key
=>
$value
) {
if
(
is_array
(
$value
)){
$date
[
$key
] = serialize(
$value
);
}
else
{
$date
[
$key
] =
$value
;
}
}
}
if
(
$method
==
"GET"
) {
$query
=
$date
? http_build_query(
$date
) :
''
;
$path
.=
"?"
.
$query
;
}
else
{
$query
= json_encode(
$date
);
}
$cookie
=
"token={$_COOKIE['token']}; session={$_COOKIE['session']}"
;
$out
=
$method
.
" "
.
$path
.
" HTTP/1.1\r\n"
;
$out
.=
"HOST: "
.
$host
.
"\r\n"
;
if
(
$method
==
"POST"
) {
$out
.=
"Content-Length:"
.
strlen
(
$query
).
"\r\n"
;
}
$out
.=
"Accept: application/json, text/plain, */*\r\n"
;
$out
.=
"Access-Control-Allow-Credentials: true\r\n"
;
$out
.=
"Content-Type: application/x-www-form-urlencoded\r\n"
;
$out
.=
"Cookie: "
.
$cookie
.
"\r\n"
;
$out
.=
"Connection: Close\r\n\r\n"
;
if
(
$method
==
"POST"
) {
$out
.=
$query
;
}
fputs
(
$fp
,
$out
);
usleep(500);
/*
while
(!
feof
(
$fp
)) {
echo
fgets
(
$fp
, 128);
}*/
fclose(
$fp
);
return
true;
}
欢迎光临 PHP开发笔记 (http://phpvi.com/) |
Powered by Discuz! 6.1.0 |