Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curl: Saving a file instead of opening it

I'm calling an API that sends me this response:

HTTP/1.1 200 OK\r\n
Date: Fri, 24 Jul 2015 06:30:16 GMT\r\n
Server: Apache/2.2.26 (Unix) mod_ssl/2.2.26 OpenSSL/0.9.8e-fips-rhel5 mod_mono/2.6.3 mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635 PHP/5.4.22 mod_perl/2.0.6 Perl/v5.8.8\r\n
X-Powered-By: PHP/5.4.22\r\n
Expires: \r\n
Cache-Control: max-age=0, private\r\n
Pragma: \r\n
Content-Disposition: attachment; filename="LVDox-Master.docx"\r\n
X-Content-Type-Options: nosniff\r\n
ETag: d41d8cd98f00b204e9800998ecf8427e\r\n
Content-Length: 68720\r\n
Vary: Accept-Encoding,User-Agent\r\n
Connection: close\r\n
Content-Type: application/octet-stream\r\n
\r\n
PK\x03\x04\x14\x00\x06\x00\x08\x00\x00\x00!\x000\x1FÎò¡\x01\x00\x00ß\x08\x00\x00\x13\x00\x08\x02[Content_Types].xml ¢\x04\x02( \x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\
...
... (etc)

If I use this code the file is sent to the user and everything works fine:

list($headers, $content) = explode("\r\n\r\n", $result ,2);
foreach (explode("\r\n",$headers) as $header)
{
    header($header);
}

//return the nonheader data
return trim($content);

But now, I would like to save the file somewhere else so my script can work on it (rename it etc), so I don't want to directly send it to the user.

I've tried to comment the header($header); part, and do something like:

$content = getMyFile();
$file = fopen('MYTEST.docx', "w+");
fputs($file, $content);
fclose($file);

But the resulting file is not readable (it seems to be corrupted).

Do you have any idea of what could cause this problem?

Thanks in advance.

like image 873
Vico Avatar asked Jul 24 '15 06:07

Vico


1 Answers

You need to specify content length for fputs for it to be binary safe.

In this case you could try fputs($file, $content, 68720);

And ultimately provide the length from the header.

Also I would suggest opening file in binary mode by using fopen('MYTEST.docx', "wb"); especially in case you are running your code on Windows.

like image 106
D.K. Avatar answered Oct 13 '22 18:10

D.K.