PHP readfile from external server

筅森魡賤 提交于 2019-12-10 22:32:51

问题


I've got a problem with readfile() from external server. Downloaded file is always broken and has size about 3,4kb. It's working on local host.

1st:

$file_name = $_POST['myname'];
readfile("http://www.ftj.eu/.../3n.pdf");
header("Content-Disposition: attachment; filename=$file_name" .date("m-d-y") . ".pdf");

2nd:

Do you know why it isn't working even on local host?:

readfile("3n.pdf");
header("Content-Disposition: attachment; filename=$_POST['myname']" .date("m-d-y") . ".pdf");

Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

Please help me.

EDIT:

help me make readfile from external url working.


回答1:


You have a syntax error, not a problem with readfile() as @Will already mentioned.

Replace this :

header("Content-Disposition: attachment; filename=$_POST['myname']" .date("m-d-y") . ".pdf");

With this (adding the curly braces around $_POST['myname']):

header("Content-Disposition: attachment; filename={$_POST['myname']}" .date("m-d-y") . ".pdf");
                                                  ^                ^

Edit:

As for readfile() from an external URL, this is what the PHP Manual has to say about it :

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

What that means is that you have to enable allow_url_fopen in your php.ini or you can use curl to download the file on your server then serve it to your clients.

Example using curl :

<?php 
    $remote_file_url = 'http://www.ftj.eu/.../3n.pdf';
    $downloadedFileName = "your_pdf_file.pdf";

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $remote_file_url);
    $downloadedFile = fopen($downloadedFileName, 'w+');
    curl_setopt($ch, CURLOPT_FILE, $downloadedFile);
    curl_exec ($ch);

    curl_close ($ch);
    fclose($downloadedFile);

    readfile($downloadedFileName);
    header("Content-Disposition: attachment; filename={$_POST['myname']}" .date("m-d-y") . ".pdf");



回答2:


Probably your server is set to not open remote files, so you can not use fopen, readfile and similar commands on it unless you change its configuration.



来源:https://stackoverflow.com/questions/12882878/php-readfile-from-external-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!