PHP readfile() of external URL

40,888

Solution 1

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

Solution 2

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.

Share:
40,888

Related videos on Youtube

user583311
Author by

user583311

Updated on May 16, 2022

Comments

  • user583311
    user583311 1 day

    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');
    
    • netcoder
      netcoder over 11 years
      Try it and/or RTM: "A URL can be used as a filename with this function if the fopen wrappers have been enabled." ;-)
  • user583311
    user583311 over 11 years
    In both solutions there is some problem with filesize or something else, because is not working.
  • Jacob Relkin
    Jacob Relkin over 11 years
    @user583311 What seems to be the problem?
  • Mchl
    Mchl over 11 years
    @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
  • user583311
    user583311 over 11 years
    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.
  • Mchl
    Mchl over 11 years
    What are the contents of this file? I'm pretty sure you can open it in text editor and see PHP's error message.
  • user583311
    user583311 over 11 years
    As I say before, It works with a local file. No erros, as far I can see.
  • Mchl
    Mchl over 11 years
    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.
  • Brad
    Brad over 6 years
    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.