Warning gzuncompress data error in

PHP has its own function to work with gzip archives. I wrote the following code: error_reporting(E_ALL); $f = file_get_contents('http://spiderbites.nytimes.com/sitemaps/www.nytimes.com/sitemap.xml...

PHP has its own function to work with gzip archives. I wrote the following code:

error_reporting(E_ALL);
$f = file_get_contents('http://spiderbites.nytimes.com/sitemaps/www.nytimes.com/sitemap.xml.gz');
echo $f;
$f = gzuncompress($f);
echo "<hr>";
echo $f;

First echo normally outputs the compressed file with proper header (at least first two bytes are correct). If I’d download this file with my browser I can unzip it easily.

However gzuncompress thrown Warning: gzuncompress(): data error in /home/path/to/script.php on line 5

Can anyone point me to the right direction to solve this problem?

EDIT:

The part of phpinfo() output

enter image description here

asked Dec 29, 2014 at 16:32

Vlada Katlinskaya's user avatar

6

Or you could just use the right decompression function, gzdecode().

answered Dec 29, 2014 at 16:52

mario's user avatar

mariomario

143k20 gold badges236 silver badges288 bronze badges

4

Note that gzuncompress() may not decompress some compressed strings and return a Data Error.

The problem could be that the outside compressed string has a CRC32 checksum at the end of the file instead of Adler-32, like PHP expects.

(http://php.net/manual/en/function.gzuncompress.php#79042)

That could be an option of why it does not work.

Try with his code:

function gzuncompress_crc32($data) {
     $f = tempnam('/tmp', 'gz_fix');
     file_put_contents($f, "x1fx8bx08x00x00x00x00x00" . $data);
     return file_get_contents('compress.zlib://' . $f);
}

Modify your code in this:

error_reporting(E_ALL);
$f = file_get_contents('http://spiderbites.nytimes.com/sitemaps/www.nytimes.com/sitemap.xml.gz');
echo $f;
$f = gzuncompress_crc32($f);
echo "<hr>";
echo $f;

As far as I have tested locally, it does not give the error anymore.

Community's user avatar

answered Dec 29, 2014 at 16:39

GiamPy's user avatar

GiamPyGiamPy

3,5132 gold badges29 silver badges49 bronze badges

vqmod/xml/vqmod_ocshop_cacher_turbo_lite.xml

Вот так и у меня проблемма появилась такая же как описанно, заметил что данная проблемма появляется когда в продуктах используются

картинки с расширением png.

От превой проблеммы избавлся сменив расширение картинки на .jpg благо она одна была,

а вот сейчас вернее вчера добавил товары и спарсил фотки от поставика и они оказались все .png  и ерачит ошибка,

поправил вернее закоментил во vqmod/xml/vqmod_ocshop_cacher_turbo_lite.xml все что относится

Уберите в vqmodе кешера секции, которые отвечают за compress uncompress

однако проблемма осталась только вот другого плана

Warning: mysql_query() expects parameter 2 to be resource, boolean given in /var/www/user8627/data/www/мой сайт/system/database/mysql.php on line 14

Warning: mysql_query() expects parameter 2 to be resource, boolean given in /var/www/user8627/data/www/мой сайт/system/database/mysql.php on line 15

Warning: mysql_query() expects parameter 2 to be resource, boolean given in /var/www/user8627/data/www/мой сайт/system/database/mysql.php on line 16

Warning: mysql_query() expects parameter 2 to be resource, boolean given in /var/www/user8627/data/www/мой сайт/system/database/mysql.php on line 17

Notice: Trying to get property of non-object in /var/www/user8627/data/www/мой сайт/index.php on line 54

Notice: Trying to get property of non-object in /var/www/user8627/data/www/мой сайт/index.php on line 63

Warning: Invalid argument supplied for foreach() in /var/www/user8627/data/www/мой сайт/index.php on line 63

Notice: Trying to get property of non-object in /var/www/user8627/data/www/мой сайт/index.php on line 71

нету соединения с базой.

Но все таки почему изза расширения .png вылазит данная ошибка

Warning: gzuncompress() [function.gzuncompress]: data error in /home/xxxxxxxx/vqmod/vqcache/vq2-system_library_cache.php on line 11

, я кнечно понимаю что надо расширение .jpg но что я могу сделать если поставщик сделал пнг.

Может надо где то настройки расширений поправить для пнг что бы читалось или кэшировалось, ведь в баннер добавляю все ок как только в продукты все бяка.

Bug #39616 gzuncompress() data error
Submitted: 2006-11-24 12:07 UTC Modified: 2015-03-13 09:49 UTC
From: emanuele at fondani dot it Assigned:
Status: Not a bug Package: Zlib related
PHP Version: 4.*, 5.* OS: Windows/Linux
Private report: No CVE-ID: None

 [2006-11-24 12:07 UTC] emanuele at fondani dot it

Description:
------------
PHP reports data error on function gzuncompress() when decompressing a particular gzipped string (see Reproduce code).

Reproduce code:
---------------
<?php
$gz_base64 = "SIl8VkFy2zgQvOsVc6S2YoQgQILcmx3HKaWcuMrW7iWVAyLBClIUqaUkp8rPyDf8hHwmxz3sI7YHICw5zm6lYkHwYNAz3T3w2Xzy8kKSpPntROZCV3lNOf6ltamkKAutSBZNI0xlELme5LSavHxzI2m1xXq+4B9fJ9ml3fnO0tVq5afzL5OTWuSlqelECl3UFc3PJ9k7Nyz61i3/oaKg9/2dW38aHBV5XvGJlxdFhFJo0eRVFaCkdVGKMq8YSV2KIpc1I8mKcPD1HBDe4P9bHPhCUuSFpK+ogt7Rh485LSeSPE1iCpJKGmQoaD2pZRliH7fayc2kEI1pcPwxvjBKKEBI8YcdDj/jHqoROM5KLSPwcV1UtWiamk/VWphcVYz8JOeLDXfvQ/ZO3Iiz2elUldmb2RVNP87fHjWjEXUNQCHnuFa1EY3SzfOcsgo5s4ur9+czil39H3C6wZlS/Te47PL1+6vL09RlUaLPoFPUWqO/TSVyhRLLXBhV0okBwKIqaXBoDFOSqJhUDVjTJRmWljFHvU877WOMqvBpjvlJO23i5JBGSyUkZHZIM4YcsqSQQxaAEwYqNqXCIU2gR+jSEMtdV5As619yGbeIVKFmI7jhRV6DeU7aaKGg4nGj/UXEuCGlFoVUKaR83EBInQtZqqOQm3DfaqKrRlQN86JFZTSNiJ4gC8pLKlEgNFeR3HEtywYLyZ5RBgQ1Jrk3EAxJwrYfsllLq2G/2fS06Lutb70dprLOHD1cTIsy67ulpz+nymR+KvPsjn/Y7/Q3bfctbbxbOkLAau+GwY7K1RFTaYTWOtoYnTVVrSEVJdhTEpU3ZfEoNzQBauNVDqYCrodru8C02Fka/O1UopbM73f+RbgEkXWjDeGzqVUTpsvKbXe+7xxt+gWK+YxC7HdWLppWgfdxsqlKysM4kRqeKpoytEZI9DtMNAiR9xjHNYyJ4Ze9enV1OW2gkGw+baCX7HSaZ3Q9u5j9MZ9FVDlPuxy2YDyhmDqlq5owJLeLfd9ackvy3cIOHigJsN3Q+d8Z6vw3RpEXJt697bue/tpzYdMTpaGSzNPOrR+/bdxAi/3hl23AgSzRw1VMc8zvigkOnIFf6K4ODB8fy1UTj935acEBd/EDrG89bQa3QWPJ0pLzfLK7nZ1i2OvsJCVBBbrUoV6+DaXSq/FqBrHed7Z14lCuZvYRPOvozm9B+NK17Te73fqto4XHBUu8LIf4Ro3ULD676YnG2NxyV4bhR/x2F+tynRvw1GzdYF/EXxzaw93RT7uDjqx91w+2u7f02XKhP9UVmhMHLMuoNpFS1+3srifLmNdIgRIGe89KHCFHJVRJWGNrUiNo333zHcPvV784NgpIlYkVdDMwXmJcaq4cGoIL08ba4gHugf1AhjFF6hdzf38PwrSsoWl4GGpMxkm7aP9xyVKNx9HJOw+E3KohmXPp/FODHh81tY5HoZK9bddolSO72dg2tczStn8mn0I14xBYeLf7QQ/nDiMI46zKcL/9LoC0lkJlDzMc3+1+zhDEXybUiwES8nRtb6OObx2ajoxnPah6QRdueK7fMh+Bd7ZbIr2C8Zvs3NPoGSYq7bplWp0OIBThB5HJ5OR0zrP9T9hIrYtbq5WjjgU/iuBXoovi4SWe2yjaKBXYMLQe03lYRzJ2cGVwOieqjqvKjRqrghPd4IEjaAdDBhUATMOOomCfCvZZ2Z9SPB1peTkqEjPqdsr0g2UWkTYYkrZd7LsxGbx4kEg0bYjx3RE4VY/p1gg+iCMq4KkAxNGxSlXj8ABV9363hxyohzgH7gML3g/uMDv4YRzFjJpLZg3XLH2YYvE7zMBvznbjsBnZD/vH0wPqGolFq2H3oEH+m6DIgiCj6MLITftPZ3MeTRWngIsPAmGw7jxsxYMVo88fvQhV6s39PWYwS1ahhRWDT1ZMW9GRzzQNM46lH5sVvDf8BrQ7Hnfxi13iTYLZDxtpgfG4Dq/8vwIMAJ6YHA==";
$gz = base64_decode($gz_base64);

echo gzuncompress($gz);
?>

Expected result:
----------------
BT
/F1 1 Tf
10.4608 0 0 10.4608 761.5243 1299.7671 Tm
0 g
/GS1 gs
0 Tc
0 Tw
(Latina Oggi)Tj
-8.0578 -1.4286 TD
(Mercoled? 22 Novembre 2006)Tj
/F2 1 Tf
24.9066 0 0 24.9066 25.5063 1285.2018 Tm
(26)Tj
ET
0 G
0 J 0 j 1.021 w 10 M []0 d
1 i 
25.506 1317.202 m
815.021 1317.202 l
S
2.979 w 
25.506 1273.366 m
815.02 1273.366 l
S
BT
/F3 1 Tf
22.9141 0 0 22.9141 268.9982 1284.7036 Tm
-0.0217 Tc
[(M.S.BIA)35(GIO )]TJ
/F2 1 Tf
29.8879 0 0 29.8879 387.9349 1284.7036 Tm
-0.0167 Tc
(FONDI )Tj
/F3 1 Tf
22.9141 0 0 22.9141 490.0532 1284.7036 Tm
-0.0217 Tc
(LENOLA)Tj
ET
0.5 G
428.844 1096.031 250.735 -729.265 re
S
0 G
1.021 w 
695.245 710.477 m
815.021 710.477 l
695.245 365.272 m
815.021 365.272 l
25.506 710.477 m
413.178 710.477 l
25.506 365.272 m
413.178 365.272 l
S
0.7 g
753.474 982.457 61.546 -10.461 re
f
0.3 G
427.349 208.36 m
494.322 208.36 l
427.349 208.36 m
427.349 114.213 l
427.35 114.213 m
480.153 114.213 l
S
0.3 g
469.692 124.674 10.461 -10.461 re
f
BT
/F2 1 Tf
23.9103 0 0 23.9103 159.9113 1237.7397 Tm
0 g
-0.0282 Tw
[(Il gruppo consiliar)18(e ?F)25(ondi V)37(i)10(v)10(a? ? sul piede di guerra)]TJ
/F4 1 Tf
57.4446 0 0 61.7684 253.06 1180.9526 Tm
-0.053 Tc
-0.0078 Tw
[(?Raccolta rif)19.9(iuti,)]TJ
-0.8947 -0.9839 TD
(gestione poco chiara?)Tj
10.672 0 0 10.3611 25.5063 1149.8295 Tm
0.1124 Tc
0.2495 Tw
[(RA)39.7(CCOL)91.5(T)92.4(A)0( RIFIUTI,)]TJ
0 -1.0096 TD
-0.0084 Tc
0.269 Tw
(scuola ed incarichi esterni:)Tj
T*
0.1027 Tw
[(sono questi)-344.2(i temi)-344.2(per cui)-344.2(il)]TJ
T*
-0.0216 Tw
[(gruppo consigliare di ?F)14.8(ondi)]TJ
T*
-0.0039 Tw
[(vi)24.8(v)24.8(a? si prepara a dare batta)-8.4(-)]TJ
T*
0.1454 Tw
(glia in Consiglio comunale.)Tj
T*
0.1453 Tw
(In vista dell?assise cittadina)Tj
T*
0.1935 Tw
[(che)-435(si terr?)-435(v)14.8(enerd? sera,)-435(il)]TJ
T*
0.0246 Tw
[(gruppo di minoranza ha pre)-8.4(-)]TJ
T*
-0.0067 Tc
0.3687 Tw
(sentato all?amministrazione)Tj
T*
-0.0086 Tc
0.2454 Tw
(comunale un?interrogazione)Tj
T*
-0.0084 Tc
0.3539 Tw
[(in cui)-595.4(si chiede)-595.4(maggiore)]TJ
T*
0.1772 Tw
[(chiarezza)-418.7(sulla gestione)-418.7(del)]TJ
T*
-0.0132 Tw
[(servizio di raccolta dei rif)19.9(iuti)]TJ
T*
-0.0784 Tw
[(attualmente appaltato alla so)-8.4(-)]TJ
T*
0.2398 Tw
[(ciet? ?De V)59.6(izia?.)-481.3(?I sotto)-8.4(-)]TJ
T*
-0.0252 Tw
[(scritti Raf)24.8(fele De Bonis, Fer)-8.4(-)]TJ
T*
0.1504 Tw
[(nando)-391.9(Di F)14.8(azio)-391.9(ed)-391.9(Arnaldo)]TJ
T*
0.0127 Tw
[(F)14.8(aiola - si le)14.8(gge nell?interro)-8.4(-)]TJ
T*
-0.0086 Tc
-0.031 Tw
[(gazione a f)19.7(irma dei tre consi)-8.6(-)]TJ
T*
0.0734 Tw
[(glieri - chiedono)-314.9(che v)14.6(enga)-8.6(-)]TJ
T*
-0.0084 Tc
0.2059 Tw
[(no f)9.9(atte)-447.5(alcune v)14.8(erif)19.9(iche)-447.5(in)]TJ
T*
0.0389 Tw
[(merito alla societ? De V)59.6(izia.)]TJ
T*
0.0636 Tw
(Innanzitutto occorre chiarire)Tj
T*
0.1103 Tw
[(se)-351.9(la ditta)-351.9(stia rispettando)-351.9(il)]TJ
T*
0.2527 Tw
[(contratto)-494.2(sottoscritto con)-494.2(il)]TJ
T*
-0.0032 Tw
(comune ed in particolare se i)Tj
T*
0.106 Tw
[(mezzi per)-347.6(la raccolta)-347.6(dei ri)-8.4(-)]TJ
T*
0.0783 Tw
[(f)19.9(iuti)-319.8(oltre)-319.8(ad essere)-319.8(a)-319.8(norma)]TJ

Actual result:
--------------
<br />
<b>Warning</b>:  gzuncompress() [<a href='function.gzuncompress'>function.gzuncompress</a>]: data error in <b>C:Inetpubwwwroottesttest2.php</b> on line <b>9</b><br />


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports

 [2006-11-24 12:24 UTC] tony2001@php.net

Sorry, but your problem does not imply a bug in PHP itself.  For a
list of more appropriate places to ask for help using PHP, please
visit http://www.php.net/support.php as this bug system is not the
appropriate forum for asking support questions.  Due to the volume
of reports we can not explain in detail here why your report is not
a bug.  The support channels will be able to provide an explanation
for you.

Thank you for your interest in PHP.


 [2006-11-24 12:36 UTC] emanuele at fondani dot it

Please be more specific. Where can I get more information about this problem?
What are the "support channels" you mean? Can you suggest a link?

Thank you

 [2006-11-27 12:07 UTC] mgf@php.net

There's a suggested link in tony2001's message.  Mailing lists and newsgroups are usually good support channels.

 [2009-11-20 09:03 UTC] emanuele at fondani dot it

I found that the issue is due to the fact that in some cases in the gzipped pdf stream the zlib stream header (see RFC 1950) is missing or invalid, and the gzuncompress() function cannot decompress data.

Here's my workaround to fix the problem: I wrote a new ZlibDecompress class in PHP from some original C++ code by Mark Adler taken from the official zlib site, which uses the standard algorithm and always decompress the string correctly, ignoring the zlib stream header, as it contains only CRC data. 
Obviously this PHP class is much more slower than gzuncompress function, because it is not compiled, so I use it only when gzuncompress fails. For pdf files this happens only in a few cases, so this is a good compromise for me.

If anyone is interested please contact me by email and I will send the class file.

 [2015-03-13 09:49 UTC] mike@php.net

Did you try zlib_decode() yet? (since PHP-5.4)

579 votes

1 answers

Get the solution ↓↓↓

I’m currently building a web app that’s pulling data from an API. The API uses XML as form of accepting requests and sending responses. I’ve got he web app working perfectly fine on my WAMP server. I even deployed it online on a free PHP web server as way of testing it and it works seamlessly. However when I deployed it the live server, I got the following errors in my php log file.

Tue Apr 07 17:28:12 2015] [error] [client 94.236.7.190] PHP Notice:
Undefined offset: 1 in /home/jdsites/camping.blacks.co.uk/api.php on
line 214
[Tue Apr 07 17:28:12 2015] [error] [client 94.236.7.190] PHP Warning: gzuncompress(): data error in
/home/jdsites/camping.blacks.co.uk/api.php on line 214
[Tue Apr 07 17:28:12 2015] [error] [client 94.236.7.190] PHP Notice: Trying to get property of non-object in
/home/jdsites/camping.blacks.co.uk/api.php on line 89
[Tue Apr 07 17:28:12 2015] [error] [client 94.236.7.190] PHP Notice: Trying to get property of non-object in
/home/jdsites/camping.blacks.co.uk/api.php on line 89
[Tue Apr 07 17:28:12 2015] [error] [client 94.236.7.190] PHP Notice: Trying to get property of non-object in
/home/jdsites/camping.blacks.co.uk/api.php on line 89

This is the PHP code in my script:

// decode the attachment data and this should return a valid xml string
line 214: $attachment_xml = gzuncompress(base64_decode($matches[1]));
line 215: $responseXml = new SimpleXMLElement($attachment_xml);

I Can’t seem to figure out the issue :-|

2022-05-19

Write your answer


42

votes

Answer

Solution:

Your code misses fundamental error checking (sorry for the boldness here :)).

// decode the attachment data and this should return a valid xml string
$attachment_xml = gzuncompress(base64_decode($matches[1]));
$responseXml = new SimpleXMLElement($attachment_xml);

This might be working PHP code but only under certain circumstances. This is exactly what you experience: On your WAMP box, it’s fine but elsewhere it spits a lot of errors and warnings. Let’s see where the problem is first:

$match = $matches[1];
if (!strlen($match)) {
    throw new UnexpectedValueException('No match found');
}

$compress = base64_decode($match);
if (false === $compress) {
    throw new RuntimeException('Failed to decode base64');
}

$uncompress = gzuncompress($compressed);
if (false === $uncompress) {
    throw new RuntimeException('Failed to gzuncompress');
}

$xml = simplexml_load_string($uncompress);
if (false === $xml) {
    throw new RuntimeException('Failed to parse XML');
}

As this code obviously shows, it will tell on its own which operation it executes fails because each operation’s return value is properly checked before the code continues.

As you interact here with foreign data this is really important because an error in the data could be intermingled into the different encodings you have here:

  • base64
  • gzip
  • XML

at each stage something just can fail, but you didn’t even check in your original code.

Next to assuming that input data is always faulty, the code also checks for the match, that is the unknown encoding you’re using you parse out from something I guess with a regular expression. So it’s important you find the first place of error as early as possible. Otherwise you perhaps look in the wrong place to find the cause of error.


Share solution ↓

Additional Information:

Date the issue was resolved:

2022-05-19

Link To Source

Link To Answer
People are also looking for solutions of the problem: integrity constraint violation: 1452 cannot add or update a child row: a foreign key constraint fails

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.


Similar questions

Find the answer in similar questions on our website.

  • Автор темы
  • #1

Переношу сайты на другой хостинг (в США). Возникла проблема. Страницы с текстом, хранящиеся в gzip не открываются с помощью

PHP:

$file=file_put_contents($put_do_fila);
$text=gzuncompress(stripslashes($file));
echo $text;

Получаю ошибку
Warning: gzuncompress() [function.gzuncompress]: data error in /……dex.php on line 102

На старом бывшем хостинге mchost и дома на компе все открывается. Пробовал перезакачивать файлы — проблема не ушла.

  • #2

фаилы в UTF-8?
— я бы проверил кодировку
— потом бы попытался прочитать фаил и выдать на страницу дамп
— если дам есть то значит внутри проблема
— может где есть 1 лишний символ до начала упаковки то тогда будет ошибка
— может с буфферизацией проблема

вот пример как у меня работает
мой класс

<?php
/**
* $Revision: 11 $
* $Author: CrashX $
* $Date: 2010-02-02 14:27:01 +0600 (Вт, 02 фев 2010)$
* $Id: gzip.php 11 2010-02-02 08:52:10Z CrashX $
* Copyright © CrashX <XSiteCMS@gmail.com>
* Всі права захищено © CrashX
*/
if(!defined(‘_SHELL’)) die();

/* Класс GZip (сжатия страниц) */
class GZip {
var $version=0.02;

//BEGIN class ZIP
var $encoding=false;
var $data=»;
var $size=»;
var $crc32=»;
var $http_encoding=false;

/**
* Конфигурация определение поддержки GZip браузером и сервером
* @return boolean
*/
function config() {
if(GZIP && (isset($_SERVER[‘HTTP_ACCEPT_ENCODING’]) || isset($_SERVER[‘HTTP_TE’]) ):(
if(headers_sent() || connection_aborted():(
return false;
endif;
if(isset($_SERVER[‘HTTP_ACCEPT_ENCODING’]):(
$this->http_encoding=$_SERVER[‘HTTP_ACCEPT_ENCODING’];
elseif(isset($_SERVER[‘HTTP_TE’]):(
$this->http_encoding=$_SERVER[‘HTTP_TE’];
endif;
if(strpos($this->http_encoding,’x-gzip’) !== false:(
$this->encoding=»x-gzip»;
endif;
if(strpos($this->http_encoding,’gzip’) !== false:(
$this->encoding=»gzip»;
endif;
if(extension_loaded(‘zlib’) && $this->encoding:(
ob_start();
ob_implicit_flush(0);
return true;
endif;
endif;

return false;
}

/**
* Сжатия данных
* @param string данные для сжатия
* @return string
*/
function compress($page) {
if(GZIP:(
if($this->encoding && function_exists(«gzcompress»):(
$this->data=ob_get_contents();
if((strpos($_SERVER[‘HTTP_USER_AGENT’], «MSIE 5»)>0 || strpos($_SERVER[‘HTTP_USER_AGENT’], «MSIE 6.0»)>0) && strpos($_SERVER[‘HTTP_USER_AGENT’], «Opera»)===false:(
$this->data=str_repeat(» «, 2048).»rn».$this->data;
endif;
ob_end_clean();
$this->data.=$page;
$this->crc32=crc32($this->data);
$this->data=gzcompress($this->data,GZIP);
$this->size=strlen($this->data);
$this->data=substr($this->data,0,$this->size-4);
header(«Content-Encoding: «.$this->encoding);
header(«Content-Length: «.$this->size);
echo «x1fx8bx08x00x00x00x00x00»;
echo $this->data;
echo pack(‘V’,$this->crc32);
echo pack(‘V’,$this->size);
echo «n<!— Use «.$this->encoding.» compress «.GZIP.» —>»;
echo «n<!— Not compress length: «.strlen($page).» —>»;
echo «n<!— Compressed length: «.$this->size.» —>»;
exit();
endif;
endif;
return $page;
}

}
//END class GZIP
?>

пример

//если GZip включен
if(GZIP:( //GZIP степень сжатия если 0 то выкл
//загрузка класса GZip, его инициализация и конфигурирование
$engine->extend($engine->gzip);
$engine->gzip->config();
$engine->gzip->compress($engine->template->result[‘template’]);

//$engine->template->result[‘template’] — это все данные подлежашие упаковке
endif;
echo $engine->template->result[‘template’];
$engine->template->unload();
$engine->template->clear(‘template’);
exit();

  • Автор темы
  • #3

Кодировка всего сp1251. Архивиование делалось дома, надо только извлечь данные.

Самое прикольное — создал отдельную папку и забросил туда файл для разархивирования и создал маленький скриптик — все работает пучком. А в скрипте а той же строке — ошибка.

  • #4

если не сложно валожи скрипт, тут подправим))
так если я правильно понял это кеш в гзип?
или ты отдаешь страничку в Гзип упаковывая ее?
или что лучше выложи скрипты и пару фаилов и все)

  • Автор темы
  • #5

Лежит страничка в гзип (для уменьшения размера файлов). Скриптом обращаюсь к этой странице.
Делаю $text=file_get_contents(‘путь до файла’) .
Затем $text=gzuncompress(strip_slashes($text));
И затем если упрощенно echo $text;

В результате ругается на gzuncompress — пишет данные файла повреждены.
Сам скрипт полность отлажен, так что ошибок быть не должно. Сейчас на локалхосте разЗипил все файлы и закинул незаархивированные и убрал функцию gzuncompress.

Техподдержка хостинга предложила мне обратиться к разрабочку. :) т.е. мне самому к самому себе :).

  • #6

хотя бы 1 фаил сжаты приложи.. посмотреть для того можно ли заменить на говотовое решение с zip
еще скачай с хоста и сравни по байтово фаилы если различаются то тогда нужно к хостеру писать, тк у меня был такой хостер у когорого можно было только в 1 папку бинарные фаилы складывать

Добавлено через 32 минуты
1

$file=file_put_contents($put_do_fila);
$text=gzuncompress(stripslashes($file));
echo $text;

ЭТО СОХРАНИТЬ! а не ЧИТАТЬ!!!!!

2

// <= PHP 5
$file = file_get_contents(‘./people.txt’, true);
// > PHP 5
$file = file_get_contents(‘./people.txt’, FILE_USE_INCLUDE_PATH);

Добавлено через 35 минут

вот работает вот так

$file = ‘test.htm’;
$current = file_get_contents(stripslashes(trim($file)),FILE_USE_INCLUDE_PATH);
$text=gzuncompress($current);
echo $text;

trim нужно бы делать тоже для того что бы в конце отсеь перенос если тот есть… тк например когда я сохраняю то дописываю еще nr

еще напиши как сохраняешь, именно код напиши

  • Автор темы
  • #7

Вечером код примера архива сброшу. file_get_contents — как раз прочитать.

Архивируемые данные получаются и принимаю функциями

Код:

function load_array_dump($filename) {
$content = file_get_contents($filename);
eval(‘$array=’.gzuncompress(stripslashes($content)).’;');
return($array);
}

function save_array_dump($filename, $array) {
$dump = addslashes(gzcompress(var_export($array,true),9));
file_put_contents($filename, $dump);
}

p.s. Еще раз повторяю, что код полностью рабочий на старом хостинге и на локалхосте все отлично пахало. В данном примере могут быть маленькие косячки, т.к. это не прямоскопированный код из моего скрипта.
p.s.s. Архивирование используется только для уменьшения размера файлов при хранении на хостинге.

  • #8

Вечером код примера архива сброшу. file_get_contents — как раз прочитать.

Архивируемые данные получаются и принимаю функциями

Код:

function load_array_dump($filename) {
$content = file_get_contents($filename);
eval(‘$array=’.gzuncompress(stripslashes($content)).’;');
return($array);
}

function save_array_dump($filename, $array) {
$dump = addslashes(gzcompress(var_export($array,true),9));
file_put_contents($filename, $dump);
}

p.s. Еще раз повторяю, что код полностью рабочий на старом хостинге и на локалхосте все отлично пахало. В данном примере могут быть маленькие косячки, т.к. это не прямоскопированный код из моего скрипта.

Может у тебя eval не срабатывает? попробуй так:

PHP:

function load_array_dump($filename) {
$content = file_get_contents($filename);
return gzuncompress(stripslashes($content));
}

  • #9

попробуй как вариант поработать всемто export c dump и с буфферами, попробуй сериализовать и тп

на каждом шагде делай print_r и ищи где косяк…

PHP:

function load_array_dump($filename=null) {
$content = file_get_contents($filename,FILE_USE_INCLUDE_PATH);
//eval('$array='.gzuncompress(stripslashes($content)).';');
// не пойму зачем eval? если нужно просто присвоить то это можно и так сделать!
$array=unserialize(gzuncompress(stripslashes($content)));
// если это массив то
//$array=array();
//$array=gzuncompress(stripslashes($content));
return($array);
}
function save_array_dump($filename, $array) {

// не вижу смысла в функции var_export
//$dump = addslashes(gzcompress(var_export($array,true),9));
  $dump=addslashes(gzcompress(serialize($array),9));
  /*
   * ob_start();
var_dump($my_variable);
$my_string = ob_get_contents();
ob_end_clean();
   *
   */
file_put_contents($filename, $dump);
}

  • Автор темы
  • #10

Вечером переправил все скрипты, чтобы без gzuncompress работали. Все пашет. Всем спасибо. Тему можно закрывать.

Понравилась статья? Поделить с друзьями:
  • Warning an error occurred while opening one or more files sony vegas 16 что делать
  • Vpn error 619 windows 7
  • Vpn certificate validation failure cisco anyconnect как исправить
  • Vpn certificate error
  • Vpn adapter error