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:

[/code]

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”);
[/code]

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”);
[/code]

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:

[code lang=”php”]
if($newfile){
while(!feof($file)){

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

}
[/code]

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”);
[/code]

$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))));
[/code]

Here is the complete code:

Upload.php

[codesyntax lang=”php” title=”upload.php PHP Source Code”]<?php
// UPLOAD.PHP
if($_POST[“submit”]){
$url = trim($_POST[“url”]);
if($url){
$file = fopen($url,”rb”);
if($file){
$directory = “./downloads/”; // Directory to upload files to.
$valid_exts = array(“jpg”,”jpeg”,”gif”,”png”); // default image only extensions
$ext = end(explode(“.”,strtolower(basename($url))));
if(in_array($ext,$valid_exts)){
$rand = rand(1000,9999);
$filename = $rand . basename($url);
$newfile = fopen($directory . $filename, “wb”); // creating new file on local server
if($newfile){
while(!feof($file)){
// 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.’; }
}
?>

[/codesyntax]

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:

https://bgallz.dev/1345/php-upload-multiple-files-url/

Enjoy!

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

38 Comments

  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 http://game-script.net 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 http://topmorpg.com 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 thumbshots.org. 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

    <?php

    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
    “http://www.domain..net/65049.mp4?oh=1234&__gda__=1234”
    then it error because it’s not valid URL. So, how can I edit the php code to download this URL.
    Thanks

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

      0){
      // ... 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.

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

      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”]
    pic_resize(900,700,”../../images/business/b_”.$imgurl,”../../images/business/b_”.$imgurl);
    pic_resize(195,180,”../../images/business/b_”.$imgurl,”../../images/business/b_”.$imgurl.”_195x180″);
    pic_resize(150,95,”../../images/business/b_”.$imgurl,”../../images/business/b_”.$imgurl.”_150x95″);
    pic_resize(100,100,”../../images/business/b_”.$imgurl,”../../images/business/b_”.$imgurl.”_100x100″);
    pic_resize(80,80,”../../images/business/b_”.$imgurl,”../../images/business/b_”.$imgurl.”_80x80″);
    pic_resize(40,40,”../../images/business/b_”.$imgurl,”../../images/business/b_”.$imgurl.”_40x40″);
    [/codesyntax]

    Thanks

    • 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:
      http://bgallz.org/502/php-upload-resize-image/

      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:
      http://bgallz.org/502/php-upload-resize-image/

      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 *
Website