How to Download a File in PHP

Save

The PHP language is an interpreted scripting language commonly used to drive dynamic websites. PHP is widely deployed among web hosting providers, where it is chosen for its ease of use, tight database integration, and free availability as open-source software. If you are developing a routine that needs to read the contents of a file available on the web, then you'll need to use PHP's native features to download the file.

  • Store the name of the file to download in a variable.

    If you want to download the file available from the URL "http://www.myserver.net/myfile.txt", use the following line in your PHP script:

    $download_location = "http://www.myserver.net/myfile.txt";

  • Call PHP's "file_get_contents()" function to load the contents of the file into a string.

    To save the file's contents into the string "file_contents", use this command:

    $file_contents = file_get_contents($download_location);

  • Test your script.

    Put your PHP commands into a file named similarly to "download_test.php" and upload it to your web server. Ensure that it displays the output you expect.

    A simple test file might look like this example. This script downloads a file from another website and displays its contents:

    <?

    $mystring = file_get_contents("http://anothersite.net/testfile.txt");

    echo $mystring;

    ?>

Tips & Warnings

  • Use PHP's "fopen()" function to treat the file referenced in the URL as if it were local instead of downloading its contents into a string.
  • As a security precaution, PHP is not allowed to download files unless its configuration parameter "allow_url_fopen" is enabled.

Related Searches

References

  • Photo Credit computer with infected e-mail and bugs image by patrimonio designs from Fotolia.com
Promoted By Zergnet

Comments

You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!