windows 系統中socket擴充
windows 下可以直接修改php.ini 檔案 去掉extension=php_sockets.dll 前面的分號重啟就OK了
在linux下給PHP安裝socket擴充
| 代碼如下 |
複製代碼 |
|
#cd /home/php5.2.1/ext/sockets
#/server/php/bin/phpize
#./configure --prefix=/usr/local/php/lib --with-php-config=/server/php/bin/php-config --enable-sockets
#make
#make install
再修改/usr/local/php/etc/php.ini檔案
#extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/" (php5.4版本以上不用加擴充路徑)
extension=sockets.so |
重啟apache
好了都好了下面就開始吧
| 代碼如下 |
複製代碼 |
|
//POST提交
function socketPost($url,$data){
$postStr = '';
$postLen = '';
$out = '';
//解析域
$urlInfo = parse_url($url);
$host = $urlInfo['host'];
if(!isset($urlInfo['query'])) $urlInfo['query'] ='';
$path = $urlInfo['path'].'?'.$urlInfo['query'];
//組織資料
foreach($data as $key=>$value){
$postStr .=$key.'='.rawurlencode($value).'&';#這裡需要對post的值進行編碼,否則會出現中斷
}
$postStr = trim($postStr,"&");
$postLen = strlen($postStr);
$fp = fsockopen($host, 80, $errno, $errstr, 3);
if ($fp) {
$out .="POST ".$path." HTTP/1.0\r\n";
$out .="Host: ".$host."\r\n";
$out .= "Content-type: application/x-www-form-urlencoded\r\n";
$out .= "Content-Length: ".$postLen."\r\n"; #這裡最好加上Connection: close
$out .= "\r\n";
$out .= $postStr;
fwrite($fp, $out);
fclose($fp);
}
} |
使用方法
| 代碼如下 |
複製代碼 |
|
socketPost("提交的地址",array("username"=>"這裡是post的username","password"=>321312312));
function socketGet($url){
$urlInfo = parse_url($url);
$host = $urlInfo['host'];
if(!isset($urlInfo['query'])) $urlInfo['query'] ='';
$path = $urlInfo['path'].'?'.$urlInfo['query'];
$fp = fsockopen($host, 80, $errno, $errstr, 3);
if ($fp) {
//調用模組進行抓取資訊
$out = "GET {$path} / HTTP/1.1\r\n";
$out .= "Host: {$host}\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
fclose($fp);
}
} |
使用方法:socketGet("url");
工作需要封裝好方法方便同事調用。