I want to try connecting to a remote file and writing the output from there to a local file, this is my function:
function get_remote_file_to_cache()
{
$the
Let's try sending GET request to http://facebook.com
:
$ curl -v http://facebook.com * Rebuilt URL to: http://facebook.com/ * Hostname was NOT found in DNS cache * Trying 69.171.230.5... * Connected to facebook.com (69.171.230.5) port 80 (#0) > GET / HTTP/1.1 > User-Agent: curl/7.35.0 > Host: facebook.com > Accept: */* > < HTTP/1.1 302 Found < Location: https://facebook.com/ < Vary: Accept-Encoding < Content-Type: text/html < Date: Thu, 03 Sep 2015 16:26:34 GMT < Connection: keep-alive < Content-Length: 0 < * Connection #0 to host facebook.com left intact
What happened? It appears that Facebook redirected us from http://facebook.com
to secure https://facebook.com/
. Note what is response body length:
Content-Length: 0
It means that zero bytes will be written to xxxx--all_good.txt
. This is why the file stays empty.
Your solution is absolutelly correct:
$fp = fopen('file.txt', 'w');
curl_setopt($handle, CURLOPT_FILE, $fp);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
All you need to do is change URL to https://facebook.com/
.
Regarding other answers:
fwrite()
after curl_exec()
CURLOPT_WRITEFUNCTION
for such a simple operation which is copying contents to file.touch()
creates empty file if it doesn't exists. I think it was intention of OP.Seriously, three answers and every single one is invalid?