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.

  • 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."

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



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

  • Paste the following code into the script:

    $in = fopen("", '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.

  • 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.

  • 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


Promoted By Zergnet


You May Also Like

Related Searches

Check It Out

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

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