13

Can I use external URLs in readfile()?

    header('Content-type: application/pdf');
    header('Content-Transfer-Encoding: binary');
    header('Content-Disposition: inline; filename="'.$file.'" ');
    //header('Content-Length: ' . filesize("http:...z/pub/".$file.'.pdf'));
    @readfile("http://...z/pub/".$file.'.pdf');
user583311
  • 265
  • 3
  • 6
  • 13

2 Answers2

23

The PHP manual on readfile states:

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.

As an alternative you can also use file_get_contents:

echo file_get_contents("http://...z/pub/".$file.'.pdf');
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
  • In both solutions there is some problem with filesize or something else, because is not working. – user583311 Jan 20 '11 at 20:59
  • @user583311 What seems to be the problem? – Jacob Relkin Jan 20 '11 at 21:00
  • 2
    @user583311: 'not working' is pretty vague. At least remove the error suppressing operator (`@`) so that you can see (and tell us) WHY it is not working – Mchl Jan 20 '11 at 21:01
  • It downloads a file with 300b, and the original has 300Kb. And the script works if the URL is local. So, must be something about external URL. – user583311 Jan 20 '11 at 21:03
  • What are the contents of this file? I'm pretty sure you can open it in text editor and see PHP's error message. – Mchl Jan 20 '11 at 21:18
  • As I say before, It works with a local file. No erros, as far I can see. – user583311 Jan 20 '11 at 21:31
  • That's why I'm asking about contents of the file when the url is external. Just open it in notepad, and see what these 300 bytes are. – Mchl Jan 20 '11 at 23:11
  • This is a bad idea. By using `file_get_contents()`, you buffer the entire content in memory and then force it to be echoed out. – Brad Jan 31 '16 at 22:28
3

Yes, according to the readfile page:

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.

wajiw
  • 12,239
  • 17
  • 54
  • 73