php 實現判斷頁面或圖片是否經過gzip壓縮的方法

來源:互聯網
上載者:User
下面小編就為大家帶來一篇php 判斷頁面或圖片是否經過gzip壓縮的方法。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

使用php判斷頁面或圖片是否經過gzip壓縮方法

1.使用get_headers

頁面內容

<?phpob_start('ob_gzhandler'); // 開啟gzip,屏蔽則關閉$data = array( array('name'=>'one','value'=>1), array('name'=>'two','value'=>2), array('name'=>'three','value'=>3));header('content-type:application/json');echo json_encode($data);?>

使用get_headers判斷是否使用gzip壓縮

<?php$url = 'http://www.example.com/';var_dump(check_gzip($url));/** * 判斷url是否經過gzip壓縮 * @param String $url 來源 * @param Boolean */function check_gzip($url){ $header = get_headers($url, 1); if(isset($header['Vary']) && $header['Vary']=='Accept-Encoding'){  return true; } return false;}?>

測試結果:

當加上ob_gzhandler時,返回true,刪除後返回false

2.使用curl

圖片

<?phpheader('content-type:image/jpeg');ob_start('ob_gzhandler'); // 開啟gzip,屏蔽則關閉echo file_get_contents('test.jpg');?>

使用curl判斷是否使用gzip壓縮

<?php$url = 'http://www.example.com/';var_dump(check_gzip($url));/** * 判斷url是否經過gzip壓縮 * @param String $url 來源 * @param Boolean */function check_gzip($url){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 1);   // 輸出header資訊 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 返回的資訊不直接輸出 curl_setopt($ch, CURLOPT_ENCODING, '');  // 不限制編碼類別型 $response = curl_exec($ch); if(!curl_errno($ch)){  $info = curl_getinfo($ch);  // 擷取header  $header_size = $info['header_size'];  $header_str = substr($response, 0, $header_size);  $filter = array("\r\n", "\r");  $header_str = str_replace($filter, PHP_EOL, $header_str);  // 檢查content-encoding  preg_match('/Content-Encoding: (.*)\s/i', $header_str, $matches);  if(isset($matches[1]) && $matches[1]=='gzip'){   return true;  } } return false;}?>

測試結果:

當加上ob_gzhandler時,返回true,刪除後返回false

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


聯繫我們

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