How to Copy a File From a URL with PHP

PHP (which stands recursively for "PHP Hypertext Processor") is a powerful scripting language. It is used most commonly to develop interactive web pages, but it is also capable of scripting operations on local computers. Since it was designed from the start to be aware of the Internet, copying files from URLs with PHP can be surprisingly easy compared with other scripting languages. File input and output with URLs use the exact same functions as input and output for local files.

Instructions

    • 1

      Open a new text file, using your text editor of choice. This tutorial will assume you are using Notepad, as most users are likely to have it installed already, but many people prefer an editor with more dedicated features for programming, such as jEdit.

      Click "File" and "Save As." Name the file "copyFileFromURL.php."

    • 2

      Paste the following code into the file to declare it at as a PHP script:

      <?php

      ?>

      All the code for the rest of the tutorial will go between those two lines, which mark the beginning and end of the script.

    • 3

      Paste the following code into the script:

      $in = fopen("http://www.google.com/intl/en_ALL/images/srpr/logo1w.png", 'r');

      $out = fopen("logolw.png", 'w');

      This opens both the URL from which you will be downloading and a local file to which you will store it. In this case, it uses the Google logo, but any valid URL will do. Simply replace the URL within the first "fopen" command with the one you would like to use, and replace the file name in the second "fopen" command with the filename you would like to use to store the file locally.

    • 4

      Paste the following code into the script immediately after the previous code:

      while (!feof($in)) {

      $buffer = fread($in, 2048);

      fwrite($out, $buffer);

      }

      This tells the script to continue reading data from the URL in two-kilobyte chunks until it reaches the end of the file, and to write that data to the local file.

      Press "Ctrl"+"S" to save your work.

    • 5

      Run the script by typing the following at a command prompt:

      php -f copyFileFromURL.php

      The file will be downloaded to the current directory. So, if you left the URLs in step 3 unmodified, the Google logo will be sitting in the directory when the script finishes.

Tips & Warnings

  • You can open a command prompt under Windows by clicking "Start," "Run," and typing "cmd."
Related Searches

References

You May Also Like

Related Ads

Check It Out

Geek Vs Geek: The Best Tech of 2014