V
V
Valery Molchanov2017-03-13 10:09:44
PHP
Valery Molchanov, 2017-03-13 10:09:44

How to properly send a file through headers for CURL?

There is a service that gives the file, here is the code:

ob_clean();
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $fileName);
readfile($pathToFile);
exit;

There is another service that needs to get a file from the first service
$url = <url к получению файла на первом сервисе>;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);

$result is set to false, the file is not transferred. I suspect that either I'm giving the wrong headers, or I'm using curl in the wrong way. How to use such a bundle correctly and will it work at all?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Pavel, 2017-03-13
@valerik606

Check for errors
The code is correct. The $result variable should contain the contents of the file.
If you are using a secure connection (HTTPS) you need to add curl options:

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

R
Rsa97, 2017-03-13
@Rsa97

header("Content-Type: ".mime_content_type($pathToFile));
header("Content-Transfer-Encoding: binary");
header("Content-Disposition: attachment; filename*=UTF-8''".str_replace('+', '%20', urlencode($fileName)));
header("Content-Length: ".filesize($pathToFile));
ob_clean();
flush();
readfile($pathToFile);

A
Alexander N++, 2017-03-13
@sanchezzzhak

1 the service should send the file via xrealpath, this is for ngnix (this is the most economical option through the script (you can even transfer the video without loading the script and the server will give everything a la ngnix as static)
2 the receiving script via curl
usually downloads files like this

$file = 'путь куда сохранить файл'
$destFile = @fopen($file, "w");
дальше curl нужно выставить след. настройки
curl_setopt($ch,CURLOPT_FILE, $destFile)
curl_setopt($ch,CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_MAXREDIRS,5);
curl_setopt($ch,CURLOPT_TIMEOUT,300);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($ch);
curl_close($ch);
fclose($destFile );

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question