PHP 使用socket 類比POST的方法

來源:互聯網
上載者:User
這篇文章主要介紹了 PHP 使用socket 類比POST的方法,結合執行個體分析了sockets 類比 POST 常用技巧,需要的朋友可以參考下

我們用到最多的類比POST請求幾乎都是使用php curl來實現了,沒考慮到PHP socket也可以實現,今天看到朋友寫了一文章,下面我來給大家分享一下PHP socket類比POST請求執行個體。

以前類比post請求俺都用PHP curl擴充實現來著,沒想過PHP socket也可以實現。最近翻了下相關資料才發現原來沒有那麼高深,只是以前一直沒有完全理解post的原理和本質而已,其實就是發送給目的程式一個標誌為post的協議串如下:

POST /目的程式url HTTP/1.1

Accept: 接收資訊格式

Referer: url來路

Accept-Language: 接收語言

Content-Type: application/x-www-form-urlencoded

Cookie: 網站cookie,不用俺過多解釋,對吧?

User-Agent: 使用者代理程式,作業系統及版本、CPU 類型、瀏覽器及版本等資訊

Host: 要發送到的主機地址

Content-Length: 發送資料的長度

Pragma: 本地是否存在緩衝

Cache-Control: 是否需要網頁緩衝

Connection: 串連狀態

username=fengdingbo&password=jb51.net //post發送的資料

我想大家對錶單的post方法提交資料應該是最熟悉不過了,例如我們想把使用者名稱和密碼發送給某個頁面的時候,填寫好相應的input框,點擊提交按鈕,最後把這個表單發送到action程式的就是以上資料。知道了這一點我想就不難了

這時候我們只需要用php的socket開啟一個連接埠,例如80連接埠,把以上資訊利用這個連接埠發送給目的程式就行了。

我們如何在一個連接埠上建立一個socket通道呢?

在PHP中是如此簡單呢!

官方給的原型:

resource fsockopen ( string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") ]]]] )

下邊是人類的理解:

fsockopen(主機名稱,連接埠號碼,錯誤號碼的&變數,錯誤提示的&變數,逾時時間)
主機名稱就是你需要發送資料的目的地;
連接埠號碼就是這個目的程式會在哪個連接埠等著你的資料;
錯誤號碼的&變數,這個是如果建立socket不成功的時候返回的錯誤編號;
錯誤提示的&變數,是錯誤的時候返回的錯誤提示資訊;
逾時時間,就是post資料之後如果對方沒有回應資訊,等待的最長時間。

如果不出意外(你正確的設定fsockopen()函數的參數)的話,一個socket通道現在已經開啟了,我們下一步需要做的就是,通過這個開啟的通道把post請求協議發給目的程式,這時候可以使用fwrite或者fputs函數中的任意一個,把post的請求格式發給fsockopen()開啟的資源控制代碼,這時候一個偉大的socket類比的post請求就誕生了。

代碼如下

<?php/** * SOCKET擴充函數 * @copyright (c) 2013 * @author Qiufeng <fengdingbo@gmail.com> * @link http://www.jb51.net * @version 1.0 */ /** * Post Request * * @param string $url  * @param array $data * @param string $referer * @return array */if ( ! function_exists('socket_post')){ function socket_post($url, $data, $referer='') { if( ! is_array($data)) { return; }  $data = http_build_query($data); $url = parse_url($url);  if ( ! isset($url['scheme']) || $url['scheme'] != 'http') { die('Error: Only HTTP request are supported !'); }  $host = $url['host']; $path = isset($url['path']) ? $url['path'] : '/';  // open a socket connection on port 80 - timeout: 30 sec $fp = fsockopen($host, 80, $errno, $errstr, 30);  if ($fp) { // send the request headers: $length = strlen($data); $POST = <<<HEADERPOST {$path} HTTP/1.1Accept: text/plain, text/htmlReferer: {$referer}Accept-Language: zh-CN,zh;q=0.8Content-Type: application/x-www-form-urlencodem Cookie: token=value; pub_cookietime=2592000; pub_sauth1=value; pub_sauth2=valueUser-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17Host: {$host}Content-Length: {$length}Pragma: no-cacheCache-Control: no-cacheConnection: closern{$data}HEADER; fwrite($fp, $POST); $result = ''; while(!feof($fp)) { // receive the results of the request $result .= fread($fp, 512); } } else { return array(  'status' => 'error',  'error' => "$errstr ($errno)"  ); }  // close the socket connection: fclose($fp);  // split the result header from the content $result = explode("rnrn", $result, 2);  // return as structured array: return array( 'status' => 'ok', 'header' => isset($result[0]) ? $result[0] : '', 'content' => isset($result[1]) ? $result[1] : '' ); }} print_r(socket_post('http://www.jb51.net/', array('name='=>'qiufeng','password'=>md5('www.jb51.net'))));/* e.g: socket_post('http://www.jb51.net', array('name='=>'qiufeng','password'=>md5('jb51.net'))); *//* End of file socket_helper.php */

實際上,當socket通道開啟時,我們傳的COOKIE是正確的話,(啟動並執行php代碼來自上邊,運行後返回的網頁出現了我的使用者名稱,說明對方網站已經承認我已經登入了)咱就可以幹N多事情,比如刷帖,刷回複等,你們懂的,對吧?

好了上面還不夠有說服力我們來看一個php socket實現圖片上傳

這個代碼有兩點要注意:

一是他是http的post 請求;

二是表單上傳協議,

下的請求 串適合任何語言.

代碼如下

<?php    $remote_server = "jb51.net";    $boundary = "---------------------".substr(md5(rand(0,32000)),0,10);      // Build the header   $header = "POST /api.php?action=twupload HTTP/1.0rn";   $header .= "Host: {$remote_server}rn";   $header .= "Content-type: multipart/form-data, boundary=$boundaryrn";    /*   // attach post vars   foreach($_POST AS $index => $value){    $data .="--$boundaryrn";    $data .= "Content-Disposition: form-data; name="".$index.""rn";    $data .= "rn".$value."rn";    $data .="--$boundaryrn";   }   */  $file_name = "aaa.jpg";   $content_type = "image/jpg";    $data = '';   // and attach the file   $data .= "--$boundaryrn";    $content_file = file_get_contents('aaa.jpg');   $data .="Content-Disposition: form-data; name="userfile"; filename="$file_name"rn";   $data .= "Content-Type: $content_typernrn";   $data .= "".$content_file."rn";   $data .="--$boundary--rn";    $header .= "Content-length: " . strlen($data) . "rnrn";      // Open the connection     $fp = fsockopen($remote_server, 80);   // then just   fputs($fp, $header.$data);   // reader   while (!feof($fp)) {   echo fgets($fp, 128);  }  fclose($fp);

總結:以上就是本篇文的全部內容,希望能對大家的學習有所協助。

聯繫我們

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