PHP Upload file from URL

Let’s say you have a form on a page with the input for URL to a file so you can upload it to your server. You can do this using PHP functions.

Here is an example of a form to upload:

[code lang=”html”]

Enter URL:


Now on upload.php we need to have PHP run an upload of the file based on the entered URL. Here is how it will look.

The form above submitted two variables, the url text, and the submit button (value “submit”). So when we start the PHP code, we check it was submitted with the submit button.

We trim the url submitted through the form using the function trim() for the url to be accessed then create a filename using the function basename(). We then check that the url exists after having these functions applied to it. This is what we are going to submit to upload.

$file = Opening the url submitted with read-only permissions. This is defined with the “rb.”

[code lang=”php”]
$file = fopen($url,”rb”);

Once we have opened the file we create a random number. This is going to be added to the file’s name when we upload it so that no two files have the same name. This is done very simply with the function rand(). Simply set the minimum and maximum for random numbers.

$newfile = Open the new file we are creating on our server. This actually creates the file on the server in the folder $directory with the random number ($rand) and the file’s name ($filename). This is done with writing permissions so that we can write the data from the url file to this one.

[code lang=”php”]
$rand = rand(1000,9999); // random number 4 digits long
$filename = $rand . basename($url); // places random number in front of the url’s base name
$newfile = fopen($directory . $filename, “wb”);

If this new file can be created, we start writing the data to the file. To do this we use the function feof(). So if the new file exists now, while we haven’t reached the end of the url file, we write this content to the one on our server. This sounds a little confusing but it is quite easy.


[code lang=”php”]

// Write the url file to the directory.
fwrite($newfile,fread($file,1024 * 8),1024 * 8);


This script basically says write the data of the url file up until we reach 8kb, to the new file we created on the server. You can adjust the maximum size in kb by changing the “8” to whatever you wish. Once it reaches the end of the file, it will stop writing.

Now let’s say we want to check for filetypes. No one wants people uploading unsafe filetypes to their server. This is a serious problem if you do not check the filetypes being uploaded. So once we establish that the file exists through the URL we are going to check its extension to match ones we allow.

$valid_exts = An array of the valid extensions we allow the user to upload. (i.e. image files).

[code lang=”php”]
$valid_exts = array(“jpg”,”jpeg”,”gif”,”png”);

$ext = We find the extension of the file by using the function explode(). This function splits the url into an array based on a seperator, in this case the seperator is a period “.” to find the trailing extension. We then set this to all lowercase because that is what our valid extensions are in. Also, we use the end() function to this array because it is possible the url has more than one period in it. We want to make sure we get JUST the extension on the end.

[code lang=”php”]
$ext = end(explode(“.”,strtolower(basename($url))));

Here is the complete code:


[codesyntax lang=”php” title=”upload.php PHP Source Code”]<?php
$url = trim($_POST[“url”]);
$file = fopen($url,”rb”);
$directory = “./downloads/”; // Directory to upload files to.
$valid_exts = array(“jpg”,”jpeg”,”gif”,”png”); // default image only extensions
$ext = end(explode(“.”,strtolower(basename($url))));
$rand = rand(1000,9999);
$filename = $rand . basename($url);
$newfile = fopen($directory . $filename, “wb”); // creating new file on local server
// Write the url file to the directory.
fwrite($newfile,fread($file,1024 * 8),1024 * 8); // write the file to the new directory at a rate of 8kb/sec. until we reach the end.
echo ‘File uploaded successfully! You can access the file here:’.”\n”;
echo ”.$directory.$filename.”;
} else { echo ‘Could not establish new file (‘.$directory.$filename.’) on local server. Be sure to CHMOD your directory to 777.’; }
} else { echo ‘Invalid file type. Please try another file.’; }
} else { echo ‘Could not locate the file: ‘.$url.”; }
} else { echo ‘Invalid URL entered. Please try again.’; }


When the form is submitted, PHP uploads the file to the directory – $directory – which is set to “./downloads/” by default. The function !feof() reads as – before reaching the end of a file. So while it hasn’t reached the end, write to $directory. Once the function returns false (when we have reached the end of the file) it will stop. The path to the file is given as “$directory.$filename.”

I have made a script for uploading multiple files from a URL or your computer’s HDD viewable here:


Filed under: PHP, Tutorials, Web ProgrammingTagged with: , , , , ,


  1. Hello, can you please post some more information on this topic? I would like to read more.

  2. I updated the post with more information.

  3. Just wantd to say thanks for having me by your site. Do you have any thoughts on for facebook apps and gaming scripts? Thought you might have heard about them and might be able to help me out. Also if you ahve a game or know of a game site I found a site that has many listed you might want to submit your favorite. Its where I find a bunch of games I like to play. Again thanks for the wonderful read.

  4. Hey:

    Just wanted to let you know that I used this tutorial to create a simple script that caches thumbnail images of web sites from It works for me since I’m not maintaining a large database of sites, and I prefer having the images cached since I’ve noticed the site up and down (have read reports of as long as a week from other users).

    It was a snap to put together with your tutorial. From start to finish I got my script working flawlessly in about an hour or so.

    Thanks very much and look forward to poking around the rest of your site.

  5. I like the blog, but could not find how to subscribe to receive the updates by email. Can you please let me know?

  6. I am brand-new to blogging and actually enjoyed your website. I am going to bookmark your blog and keep checking you out. Thanks for sharing your site.

  7. I have been a web designer for 5 years now and I have been following your blog for a long time. Always an informative read.

  8. please put <?php

    Sometime clever man do stupid mistake
    thanks for this good tutorial
    but u forget to to put


    at beginning ,

    hahaha i am a once of innocent because that 🙂
    try edit many thing this before i think ..

    • You are very right, I even included the closing php tag of “?>” in my post and didn’t include the opening php tag. My apologies, thanks for the comment!

  9. u r the best!

  10. I’m trying to save the file to the directory that i created but i dont seem to work. if i set de directory to null ok, i works fine… can you help me?

    and thank you very much for this tutorial.

    • Be sure to include a trailing slash in the directory definition. In mine it is “./downloads/”

      Also, make sure that the directory you are uploading to is writable, in FTP right click the directory and go to upload permissions and CHMOD to 777 for full access.

  11. Very thanks for this script. very cool
    I adapt it to upload video file.
    But I would like to ask some help from you, if I need to upload the URL file format like this
    then it error because it’s not valid URL. So, how can I edit the php code to download this URL.

    • So, If I prefer to do a multiple upload in one time.
      Can you tell me about this? multiple upload

  12. Can you advice me about the multiple files upload with this script please?

    • I was going to make a new post for a script to upload multiple files at once from a URL or hard drive. I’ve started the script which I will post a link to here once it is posted.

      However, for the mean time, I would recommend making an array of the files like so:

      <input type="file" name="files[]" size="25" id="file_1" />
      <input type="file" name="files[]" size="25" id="file_2" />

      … etc.

      Or, alternatively you could just name each file a different name if you know how many files you are uploading at once. The array works nicely when you don’t have a set number of files, but rather an unlimited amount.

      Then on the PHP you would do:

      // ... run upload of each file
      foreach($files as $id => $file){
      // ... upload

      I’ll post back with an updated script.

    • Thanks a lot.

  13. Hi,

    I like your script. Is there a way to rename the file after upload?

    • The filename is based off of the random number generated and the basename of the file.

      [codesyntax lang=”php”]
      $rand = rand(1000,9999);
      $filename = $rand . basename($url);

      You can change $filename to whatever you would like using the $url, which is the full URL.

  14. hi,

    how do I change size, resize. E.g:

    [codesyntax lang=”php”]


    • I am not quite sure what you are asking. You want to change the size of these images using the width,height values you have in the pic_resize() function?

      Check this post:

      That uses a width or height value and automatically calculates the other dimension based on that value to resize an image on the same scale.

  15. Very GoOd
    Thanks 🙂

  16. how can resize image before upload when i upload from url?
    can anyone help me please?

    • You would want to implement some of the concepts in this article:

      Everything would be the same except you want to take the image input field (a browse for image field) and replace it with a text input for the URL to the image.

      Then you would use the code found in this article to create a temporary image file on the server, copy that to the new resized image, and then name it.

Add a Comment

Your email address will not be published. Required fields are marked *

Comment *
Name *
Email *