Php curl disable gzip

Невозможно декодировать gzip с помощью cURL PHP

Я пытаюсь с несколькими способами, прежде чем подумать, чтобы задать этот вопрос здесь. Мне все равно не удалось. Я пытаюсь расшифровать и прочитать данные с одного сайта, использующего gzip. Я использую curl & php. Когда я пытаюсь декодировать и печатать результат, я получаю длинный список искаженных специальных символов, таких как:

 JHWkdsU01EUXdWa1pXYTFOdFZsZFRiaz VoVW14S2NGbFljRmRXYkdSWVpFZEdWRT FYVWtoWmEyaExXVlpLTm1KR1VsWmlXR2 
 PHP Warning: gzdecode(): data error in /var/www/mn.php on line 20 
 a2enmod deflate /etc/init.d/apache2 restart 
curl -sH 'Accept-encoding: gzip' http://example.com/getN.php&keyword=9999 | gunzip - 
HTTP/1.1 200 OK Server: nginx Date: Thu, 15 Oct 2015 00:41:54 GMT Content-Type: text/html; charset=utf-8 Transfer-Encoding: chunked Vary: Accept-Encoding X-Powered-By: PHP/5.4.31 X-Frame-Options: SAMEORIGIN Content-Encoding: gzip 

2 ответа

Я заметил, что ваш код имеет

curl_setopt($ch,CURLOPT_ENCODING , 'gzip'); 

и gzdecode() позже. Если указано, что он принимает кодированное содержимое, cURL автоматически обрабатывает декодирование, без необходимости вручную делать это после curl_exec() . Его возвращаемое значение уже декодировано, если вы сказали cURL принять кодированную передачу.

Тем не менее, страница, которую вы пытаетесь загрузить, на самом деле не может быть закодирована с помощью gzip, а другой метод. Как указано в руководстве, попробуйте указать пустую строку:

# Enable all supported encoding types. curl_setopt($ch, CURLOPT_ENCODING, ''); 

Это позволяет использовать все поддерживаемые типы кодирования. И не используйте gzdecode() . Результат должен быть уже декодирован.

Я пытался, что с / без (gzip, gzdecode, Accept-Encoding: gzip / deflate) все дают мне тот же результат (длинный список искаженных специальных символов) или ошибку (PHP Внимание: gzdecode (): ошибка данных в номере строки) Я также копирую код gzip и пытаюсь декодировать его вручную, либо это не работает . bwt .. У меня есть этот сайт ссылки, они декодируют мой код gzip онлайн без каких-либо проблем .. работа !! так что подтвердите мне эту проблему либо в моем коде, либо в настройках сервера. (мой сервер НЕ декодировать).

Вы не должны устанавливать длину контента самостоятельно. Если вы используете cURL для отправки HTTP POST, он рассчитает для вас длину контента и автоматически добавит необходимый заголовок Content-Length. Может быть меньше, чем strlen($data_string) если cURL сжимает содержимое. Кроме того, полностью удалите CURLOPT_HTTPHEADER и добавьте для параметра CURLOPT_POST значение true.

спасибо всем, наконец, начните работать после того, как я возьму ваш совет и удалю gzdecode и некоторые другие, и сохраните заголовок.. Примите кодировку для gzip и вот окончательный код

Ещё вопросы

  • 1 Расовые условия с использованием Office.js в Excel
  • 0 JQuery зависимые поля выбора (выбраны)
  • 1 Нужно ли разрабатывать для нескольких разрешений экрана в Unity?
  • 0 Как показать Gmail вставленные изображения на моей веб-странице
  • 0 Каков наилучший / рекомендуемый способ аутентификации пользователей, использующих отдых в Symfony?
  • 0 изображение не загружается при использовании наследования шаблонов
  • 0 Как очистить список, если ответ ложный
  • 1 Переходит на URL, но не получает ответа
  • 0 Как отладить и исправить ошибку времени выполнения, например «Необработанное исключение в 0x… in… exe: 0xC0000005: Место записи нарушения доступа 0x…»
  • 1 Использование foreach с движком представления ASP.NET внутри ASP: Repeater не работает
  • 0 Структура данных для обработки списка из 3 целых чисел
  • 0 jQuery: сортировка детей по типу
  • 0 Чтение текстового файла в структуру и отображение массива
  • 1 Как отловить ошибку HTTP по java.net.URL
  • 0 2 указателя даты в одном поле ввода
  • 1 Как условно установить деструктуризацию
  • 0 Подавить часть конструктора по умолчанию?
  • 0 Как перейти в режим мониторинга с помощью NDIS?
  • 0 Как лучше всего связать обещания при использовании решимости Angular: <>?
  • 0 Как решить конфликт с package_find из CMake?
  • 0 Скрыть блоки, которые не соответствуют контейнеру фиксированного размера
  • 0 Как textarea форматировать с HTML-тегами внутри, но не показывать?
  • 1 Новые автозаполнения Google вылетали при клике
  • 0 Правильное двоичное представление для PHP_INT_MAX + 1, с которым выполняются побитовые операции в PHP?
  • 0 Значок шеврона, направленный вверх или вниз в зависимости от положения гармошки
  • 0 Как сделать родительский ли активным, когда ребенок меняется
  • 0 Ничего не загружается, когда хеш пуст с hashchange
  • 0 Применять скрипт jquery только к определенным тегам
  • 0 Держите переменную вокруг для асинхронного лямбда
  • 0 Durandal Transition — Ожидается, что «activeView» будет нулевым, но, похоже, оно сохранит свое прежнее состояние?
  • 0 Таблица MyISAM случайно удалена, я потерял данные за 1 месяц, и на моем хосте нет резервной копии
  • 0 Управление ролями в Angularjs для отображения и скрытия вкладок
  • 1 Отладка исходного кода сгенерированного кода в IntelliJ
  • 0 C ++ Проверка правильности ввода, чтобы убедиться, что вместо буквы был введен номер
  • 0 Встроенный API возвращает String вместо JSON
  • 0 Есть ли разница между этими условными присваиваниями, которые обрабатывают значения по умолчанию?
  • 0 Как закрыть всплывающее окно при нажатии в любом месте на сайте
  • 1 Преобразовать ArrayList > в jsonArray
  • 1 java.lang.NullPointerException: попытка чтения из поля ‘android.view.View android.support.v7.widget.RecyclerView $ ViewHolder.itemView’
  • 0 остановить событие нажатия клавиши внутри iframe
  • 1 Java — проблемы с подстрокой
  • 1 Доступ к кодам категорий для объектов Index в Pandas
  • 0 Получить конкретный параметр URL
  • 0 Пагинация в Yii без базы данных
  • 0 Модуль индекса Zend Framework 2 не отображает содержимое
  • 1 Отправка писем выполняется асинхронно после возвращения результата просмотра
  • 0 Запустите .exe файл кода C, используя Eclipse
  • 1 Необязательное поле типа календаря в форме JSF
  • 0 jQuery Week Calendar без перекрывающихся событий
Читайте также:  Entryset java map методы

Источник

Compressed HTTP Requests with Curl and PHP

PHP Curl - HTTP Compression with ACCEPT_ENCODING

Compression is a vital and effective way to increase the performance of web pages and web apps. For text-based resources such as HTML files, CSS/JS files, SVG files, etc., compressing the resource at the server prior to the transmission, and decompressing it at the browser can greatly reduce the bandwidth and transfer times.

For the server and web browser, this compression step is quite opaque, in that the server compresses the resources prior to sending it to the browser, and the browser decompresses them before rendering them. The server-side software and the front-end developers do not need to handle the compression/decompression steps.

There are few compression algorithms developed through the years, and browsers and servers can negotiate the correct compression algorithm using HTTP headers.

When making an HTTP request, the browser indicates the encoding algorithms it supports in an Accept-Encoding HTTP header. If the server supports any of the specified encoding algorithms, it may decide to compress the response, and indicate that with an Content-Encoding HTTP header. IANA maintains a list of registered encoding algorithms.

The Wikipedia page for PHP is around 549 KB in size, and when it compressed with Brotli ( br ), it is only 92 KB. HTML pages, JSON responses, SVG files, CSS/JS files, and other text-based files compress well, and the computational cost it takes to compress/decompress resources is small compared to the network transfer times the compression saves.

Although browsers default to use compression when fetching resources, PHP’s HTTP clients do not. Curl, the popular HTTP Client supports encoding negotiation and opaque compressed requests, but it needs to be enabled.

$ch = curl_init('https://en.wikipedia.org/wiki/PHP'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_exec($ch);

Above is simplified example of making an HTTP request to the PHP page on Wikipedia. Curl does not use HTTP compression by default, and results in larger transfer size and request time:

curl_getinfo($ch, CURLINFO_TOTAL_TIME); // 0.81 sec curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD_T); // 548 KB

CURLINFO_SIZE_DOWNLOAD_T value reveals that Curl download 548 KB of data from the remote server. Because there is no compression support indicated by Curl (via the Accept-Encoding header), the server did not compress the response.

Читайте также:  Call init method python

Using the CURLOPT_ENCODING option, it is possible to explicitly specify the values for the Accept-Encoding header. It is not necessary manually decode the response, because Curl does it automatically. Note that setting the CURLOPT_ENCODING option is different from setting Accept-Encoding header manually. If set manually, Curl does not automatically decode the response.

CURLOPT_ENCODING value accepts a few types of values which are not known to be intuitive.

  • CURLOPT_ENCODING = null : Resets the value, disables header and automatic decoding.
  • CURLOPT_ENCODING = «» : Curl automatically sends the appropriate header based on the supported algorithms, and automatically decodes the response.
  • CURLOPT_ENCODING = «identity» : Client expects the server to not encode the response in any way.
  • CURLOPT_ENCODING = «gzip» : Client is capable of gzip algorithm.
  • CURLOPT_ENCODING = «br» : Client is capable of Brotli br algorithm.

CURLOPT_ENCODING option in fact accepts any string value, and Curl will attempt to decode it if the responding Content-Encoding header contains a known encoding algorithm.

The most useful and appropriate value for CURLOPT_ENCODING is an empty string ( «» ). It enables encoding, but does not explicitly state the algorithms. This effectively enables all algorithms supported and selected by Curl.

 $ch = curl_init('https://en.wikipedia.org/wiki/PHP'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_ENCODING, ''); curl_exec($ch);

With the CURLOPT_ENCODING=»» option, Curl now makes HTTP requests with an appropriate Accept-Encoding header, listing all algorithms it supports.

The headers sent-out can be later retrieved using curl_getinfo function:

$ch = curl_init('https://en.wikipedia.org/wiki/PHP'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_ENCODING, ''); curl_setopt($ch, CURLINFO_HEADER_OUT, true); curl_exec($ch); $headers = curl_getinfo($ch, CURLINFO_HEADER_OUT); var_dump($headers);
 string(103) "GET /wiki/PHP HTTP/2 Host: en.wikipedia.org accept: */* + accept-encoding: deflate, gzip, br, zstd

The server can opt to compress the response in one of the compression algorithms it supports. This greatly reduces the transfer time and size:

curl_getinfo($ch, CURLINFO_TOTAL_TIME); // 0.31 sec curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD_T); // 90 KB

Curl picks the compression algorithms it supports based on the options it was set at the compilation step.

Читайте также:  Python google search console api

In most distributions, PHP Curl is compiled with gzip , deflat , and br (Brotli). However, it is also possible to add support for zstd by compiling libcurl with zstd support, and recompiling PHP with the new libcurl header files.

Recent Articles on PHP.Watch

How to extend lifetime of legacy PHP applications

How to extend lifetime of legacy PHP applications

As PHP continue to evolve with new breaking changes, and while that is great for most PHP applications, there are legacy applications that can’t justify the human and financial cost of keeping up. Here is a guide on how to extend the lifetime of legacy PHP applications with security updates and maintenance.

PHP 8.2 Highlights: What

PHP 8.2 Highlights: What’s New and Changed

How to install/upgrade PHP 8.2 on Debian and Ubuntu systems

How to install/upgrade PHP 8.2 on Debian and Ubuntu systems

You will receive an email on last Wednesday of every month and on major PHP releases with new articles related to PHP, upcoming changes, new features and what’s changing in the language. No marketing emails, no selling of your contacts, no click-tracking, and one-click instant unsubscribe from any email you receive.

© 2018-2023 PHP.Watch, with ❤ from Ayesh • About PHP.Watch

Источник

Оцените статью