https 异步 post 请求

2018-09-13 15:19:09 阅读:13 编辑
/**
 * example:
 * $url = "https://www.yy.com/xx.php";
    $formdata  = ["id"=>1
    ];
    https_sock ($url,$formdata);
 * @param $url
 * @param $formdata
 */
function https_sock ($url, $formdata)
{$info = parse_url ($url);
    $host = $info ["host"];
    $port = 443;
    $path = $info ['path'];

    $poststring = "";
//build the post string
    foreach ($formdata AS $key => $val) {$poststring .= urlencode ($key) . "=" . urlencode ($val) . "&";
    }
// strip off trailing ampersand
    $poststring = substr ($poststring, 0, -1);

    $fp = fsockopen ("ssl://" . $host, $port, $errno, $errstr, $timeout = 30);

    if ($fp) {
        $head = "POST $path HTTP/1.1\r\n";
        $head .= "Host: $host\r\n";
        $head .= "Content-type: application/x-www-form-urlencoded\r\n";
        $head .= "Content-length:" . strlen ($poststring) . "\r\n";
        $head .= "Connection: close\r\n\r\n";
        $head .= $poststring . "\r\n\r\n";
        fputs ($fp, $head);
        usleep (300000); // 等待 300 ms
        fclose ($fp);
    }
}