php中socket實現GET與POST非同步提交資料

來源:互聯網
上載者:User

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");

工作需要封裝好方法方便同事調用。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.