php使用要求標頭資訊擷取遠程圖片大小

來源:互聯網
上載者:User
  1. $fp = fsockopen("www.baidu.com", 80, $errno, $errstr, 30);
  2. if ($fp) {
  3. //這裡請求設定為HEAD就行了
  4. $out = "HEAD /img/baidu_sylogo1.gif HTTP/1.1\r\n";
  5. $out .= "Host: www.baidu.com\r\n";
  6. $out .= "Connection: Close\r\n\r\n";
  7. fwrite($fp, $out);
  8. while (!feof($fp)) {
  9. $header = fgets($fp);
  10. if (stripos($header, 'Content-Length') !== false) {
  11. $size = trim(substr($header, strpos($header, ':') + 1));
  12. echo $size;
  13. }
  14. }
  15. fclose($fp);
  16. } else {
  17. echo "$errstr ($errno)";
  18. }
複製代碼

和發起GET請求一樣,只需要將請求類型GET設定為HEAD就可以了。請求的主機和路徑,修改成自己需要的即可。

小結:php也可以使用get_headers來擷取頭資訊,測試過這個函數,是GET請求,詳情參考:php函數get_headers是HEAD請求或GET請求 。另外,有的伺服器可能會屏蔽HEAD請求,如果被屏蔽了,就只能用GET請求了。

如此,可以直接用現成的函數getimagesize來取得圖片的大小。

  • 聯繫我們

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