开发者

PHP server to server file request

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 b开发者_C百科roken 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);


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


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);


If you want to downloads file from the FTP server you can use php File Transfer Protocol (FTP) extension. Please find below code:

<?php
$SERVER_ADDRESS="";
$SERVER_USERNAME="";
$SERVER_PASSWORD="";
$conn_id = ftp_connect($SERVER_ADDRESS);

// login with username and password
$login_result = ftp_login($conn_id, $SERVER_USERNAME, $SERVER_PASSWORD);

$server_file="test.pdf" //FTP server file path 
$local_file = "new.pdf"; //Local server file path 

##----- DOWNLOAD $SERVER_FILE AND SAVE IT TO $LOCAL_FILE--------##
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
    echo "Successfully written to $local_file\n";
} else {
    echo "There was a problem\n";
}

ftp_close($conn_id);
?>


Download the file with curl, then check this: http://php.net/function.readfile

It shows how to force download.


SOLVED

I ended by simply redirect the request with:

header("Location: $request");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜