来自fopen的file_put_contents创建的文件与浏览器不同

This is driving me crazy. I can download a file from internet through browser and its working fine. However if I write a script that does this for me using PHP, the file ends up being completely different (as per online diff tools).

$link = "https://torcache.net/torrent/9AE1726935FF9C08DF422CCE3C4445FC9484478B.torrent?title=[kat.cr]the.big.bang.theory.s08e24.720p.hdtv.x264.dimension.rartv";

file_put_contents($file_name, fopen( $link, 'r'));

First I tried to play around with encoding, but that should not matter as the file is binary, right? Also tried file_get_contents instead of fopen first, the same problem.

My PHP app is running on UTF-8 w/o BOM files. Can someone help? What am I doing wrong?

I think I got what you mean. The responses from torcache.net are all compressed with gzip. If you download the file from your browser, the file is automatically decoded, but if you do the same with php you get the same file but still encoded. You can use gzdecode to decodes it.

file_put_contents($file_name, gzdecode(file_get_contents($link)));

You have some errors in your code.

First you try to add a string to a variable without parentheses.

$link = "https://torcache.net/torrent/9AE1726935FF9C08DF422CCE3C4445FC9484478B.torrent?title=[kat.cr]the.big.bang.theory.s08e24.720p.hdtv.x264.dimension.rartv"

The next one you try to download that file over https. Check if your openssl is enabled and if allow_url_fopen is set correctly in your php.ini

https://secure.php.net/manual/en/features.remote-files.php

There are 3 ways to solve your problem:

  1. enable openssl for https calls

  2. Use curl and set the ssl verifier to 0

  3. Replace the https with http to make a normal call.

Option 3 is the easiest one.