Socket

本節包括支援可工作於套接字的封裝協定的上下文選項,如 tcphttpftp

自 PHP 5.1.0 起只支援一個選項,bindto,可用來指定 IP 位址(可以是 IPv4 或 IPv6)和/或 PHP 將用來訪問網路的埠號。語法是 ip:port(若果想讓系統自動選取可以將 IP 或埠號設為 0)。

注: 因 FTP 在標準運行時建立兩個套接字連線,此時不能在 bindto 選項中指定埠號。因此對於 FTP wrapper 只支援一種語法 ip:0

例子 M-1. 怎樣使用 bindto 選項的一些例子

<?php
// connect to the internet using the '192.168.0.100' IP
$opts = array('socket' =>
            array(
'bindto' => '192.168.0.100:0'));


// connect to the internet using the '192.168.0.100' IP and port '7000'
$opts = array('socket' =>
            array(
'bindto' => '192.168.0.100:7000'));


// connect to the internet using port '7000'
$opts = array('socket' =>
            array(
'bindto' => '0:7000'));


// create the context...
$context stream_context_create($opts);

// ...and use it to fetch the data
echo file_get_contents('http://www.example.com'false$context);

?>