怎麼php使用socket擷取遠程圖片

來源:互聯網
上載者:User
步驟:

1,匹配URL中的主機名稱和檔案部分

2,建立socket並串連到目標伺服器

3,構造HTTP請求並發送

4,讀取HTTP響應並解析

5,儲存內容到檔案並關閉socket串連


代碼實現如下:

<?php/* * 使用socket擷取遠端資源(網頁,圖片等) * url 資源URL * savepath 資源的儲存路徑 * return true/false */function get_remote_picture($url,$savepath="./"){    set_time_limit(0);    $pattern = '/(http:\/\/)?([^\/]+)(.+)/';    $res = preg_match($pattern, $url, $matches);    if($res == 0){        return false;    }    $host = "";//主機名稱    $file = "";//請求的檔案    if(count($matches) == 3){        $host = $matches[1];        $file = $matches[2];    }else if(count($matches) == 4){        $host = $matches[2];        $file = $matches[3];    }else{        return false;    }    $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);    $res = socket_connect($socket,gethostbyname($host),80);    if(!$res){        //echo socket_strerror(socket_last_error($socket));        socket_close($socket);        return false;    }    $request = "";    $request .= "GET $file HTTP/1.1\r\n";    $request .= "Host: $host\r\n";    $request .= "Connection: close\r\n\r\n";    $len = socket_write($socket,$request);     $response = "";    while($buf=socket_read($socket,512)){        if(strlen($buf) == 0){            break;        }        $response .= $buf;    }    if(strpos($response,"\r\n\r\n")){        $arr = explode("\r\n\r\n",$response);        if(!file_exists($savepath)){            @mkdir($savepath);        }        $savepath = rtrim($savepath,'/').'/';        file_put_contents($savepath.basename($file),$arr[1]);    }else{        socket_close($socket);        return false;    }    socket_close($socket);    return true;} /* 擷取百度logo */$url = "http://su.bdimg.com/static/superplus/img/logo_white.png";$result = get_remote_picture($url);if($result){    echo 'get remote picture success';}else{    echo 'get remote picture failed';}
  • 聯繫我們

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