一.主代码
<?php
class NSocket{
private $_url;
private $_referer;
private $_info;
private $_socket;
private $_erron;
private $_errstr;
public function __construct($url, $referer = ''){
$this->_url = $url;
$info = parse_url($url);
if(!isset($info['port'])){
$info['port'] = 80;
}
$socket = fsockopen($info['host'], $info['port'], $this->_erron, $this->_errstr, 10);
if(!$socket){
return null;
}
$this->_socket = $socket;
$this->_info = $info;
$this->_referer = $referer;
}
//socket模拟get
public function socket_get($arr){
$result = $query = '';
$query = '?'.http_build_query($arr);
$head = 'GET '.$this->_info['path'].$query.' HTTP/1.1'."\r\n";
$head .= 'Host:'.$this->_info['host']."\r\n";
$head .= "\r\n";
$code = fputs($this->_socket , $head);
while(!feof($this->_socket)){
$result .= fread($this->_socket, 512);
}
return $result;
}
//socket模拟post
public function socket_post($arr){
$data = http_build_query($arr);
$length = strlen($data);
$head = "POST {$this->_info['path']} HTTP/1.1\r\n";
$head .= "Host:{$this->_info['host']}\r\n";
$head .= "Content-Type:application/x-www-form-urlencoded\r\n";
$head .="Content-Length:{$length}\r\n";
$head .= "Connection: close\r\n\r\n";
$head .= "{$data}";
$count = fputs($this->_socket, $head);
$result = fread($this->_socket, 4096);
return $result;
}
public function getError(){
return $this->_errno.$this->_errstr;
}
}
//发送参数
$arr = array(
'code' => '123456'
);
$obj = new NSocket('http://127.0.0.1/socket/test.php');
var_dump($obj->socket_post($arr));
?>
二.test.php代码
<?php
var_dump($_POST);
var_dump($_GET);
?>