Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP server to server file request

Tags:

php

I have script-1 on server A, where user ask for a file.
I have script-2 on server B (the file repository) where I check that user can access it and return the correct file (I'm using Smart File Download http://www.zubrag.com/scripts/download.php).

I've tried cURL and file_get_contents, I've changed Content Header in various ways, but I wasn't still able to download the file.

This is my request:

$request = "http://mysite.com/download.php?f=test.pdf";

and it works fine. What should I call in script-1 to force the file be downloaded?

Some of my tries

This works, but I don't know how to handle unauthorized or broken downloads

header('Content-type: application/pdf');

$handle = fopen($request, "r");

if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);
        echo $buffer;
    }
    fclose($handle);
}

This prints the pdf code (not the text) straight in the browser (I think it's a header problem):

$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $request);
$contents = curl_exec($c);
curl_close($c);

if ($contents) return $contents;
    else return FALSE;

This generate a white page

file_get_contents($request);
like image 245
pasine Avatar asked Sep 12 '26 11:09

pasine


2 Answers

To force download, add

 header('Content-disposition: attachment');

But Note, that it's not in HTTP 1.1 spec anymore, see Uses of content-disposition in an HTTP response header first answer

like image 137
konsolenfreddy Avatar answered Sep 13 '26 23:09

konsolenfreddy


Without your code I don't know what you've tried, but you need to get the contents of the file via cURL and then save it to your server. Something like...

$url = 'http://website.com/file.pdf';
$path = '/tmp/file.pdf';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$contents = curl_exec($ch);
curl_close($ch);

file_put_contents($path, $contents);
like image 29
JamesHalsall Avatar answered Sep 14 '26 01:09

JamesHalsall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!