php中用socket類比http中post或者get提交資料的範例程式碼_PHP

來源:互聯網
上載者:User
關鍵字 php socket post
廢話不多說。直接上代碼:
sock_post.php:
複製代碼 代碼如下:
function sock_post($url, $data='') {
$url = parse_url($url);
$url['scheme'] || $url['scheme'] = 'http';
$url['host'] || $url['host'] = $_SERVER['HTTP_HOST'];
$url['path'][0] != '/' && $url['path'] = '/'.$url['path'];

$query = $data;
if(is_array($data)) $query = http_build_query($data);

$fp = @fsockopen($url['host'], $url['port'] ? $url['port'] : 80);
if (!$fp) return "Failed to open socket to $url[host]";

fputs($fp, sprintf("POST %s%s%s HTTP/1.0/n", $url['path'], $url['query'] ? "?" : "", $url['query']));
fputs($fp, "Host: $url[host]/n");
fputs($fp, "Content-type: application/x-www-form-urlencoded/n");
fputs($fp, "Content-length: " . strlen($query) . "/n");
fputs($fp, "Connection: close/n/n");

fputs($fp, "$query/n");

$line = fgets($fp,1024);

if (@!eregi("^HTTP/1/.. 200", $line)) return;

$results = "";
$inheader = 1;
while(!feof($fp)) {
$line = fgets($fp,1024);
if ($inheader && ($line == "/n" || $line == "/r/n")) {
$inheader = 0;
}elseif (!$inheader) {
$results .= $line;
}
}
fclose($fp);

return $results;
}
$re = sock_post('http://localhost/direct_post/get_post.php?id=1',array('wel'=>'hello'));
echo $re;
?>

get_post.php:
複製代碼 代碼如下:
echo "post:";
print_r($_POST);
echo 'get:';
print_r($_GET);
?>

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.