如果您可以使用 curl,以下内容应该有助于实现您的目标:
// create the curl buffered reader object with a connection to a socks5 proxy on localhost port 8888
$cbr = new \CurlBufferedReader(array(
CURLOPT_PROXY => 'socks5://127.0.0.1:8888',
// disable ssl certificate verification, you probably don't need this so I've commented it out
//CURLOPT_SSL_VERIFYPEER => false
));
// gets the body at the url up until the point specified by the callback function
$body = $cbr->get('https://stackoverflow.com/questions/24249029/php-use-socks5-proxy-with-fsockopen-ssl',
/**
* The callback function to determine whether to continue reading the body sent by the remote server
* @param string $body
*/
function (&$body) {
if (($off = strpos($body, "\nTo do that,")) !== false) {
// truncate body so that we have everything up until the newline before the string "To do that,"
$body = substr($body, 0, $off + 1);
}
return $off === false; // continue reading while true
});
echo $body;
以及相关的类:
class CurlBufferedReader {
private $body = false;
private $callback;
private $ch;
public function __construct(array $curlopts = array()) {
$this->ch = curl_init();
curl_setopt_array($this->ch, $curlopts + array(
// general curl options
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_RETURNTRANSFER => true,
// specific options to abort the connection early
CURLOPT_BUFFERSIZE => 8192,
CURLOPT_WRITEFUNCTION => array($this, 'writeFunction')
));
}
public function get($url, $callback = null) {
curl_setopt($this->ch, CURLOPT_URL, $url);
$this->callback = $callback;
if (!($success = $this->exec())) {
// errno 23 when aborted by the client
if ($this->getErrno() !== 23) {
$this->body = false;
}
}
return $this->body;
}
public function getBody() {
return $this->body;
}
public function getError() {
return curl_error($this->ch);
}
public function getErrno() {
return curl_errno($this->ch);
}
private function exec() {
$status = curl_exec($this->ch);
$this->callback = null;
return $status;
}
private function writeFunction($ch, $buffer) {
$this->body .= $buffer;
if ($this->callback && !call_user_func_array($this->callback, array(&$this->body))) {
$written = -1; // user callback requested abort
} else {
$written = strlen($buffer);
}
return $written;
}
}
它通过从远程服务器一次读取 8,192 个字节来工作。调用用户函数以读取在每个读取事件时接收到的整体。当它希望中止连接时,用户函数必须return false。同样重要的是要注意$body 是一个参考。因此,您对其所做的任何更改都会影响CurlBufferedReader::get 方法接收到的字符串。