PHP Upload file from URL
By Brian on Apr 26, 2009 with Comments 17
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:
<form action="upload.php" method="post"> Enter URL: <input type="text" name="url" size="35" /> <input type="submit" value="Submit" name="submit" /> </form>
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(). 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.”
$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.
$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:
if($newfile){
while(!feof($file)){
// 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).
$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.
$ext = end(explode(".",strtolower(basename($url))));
Here is the complete code:
Upload.php
<?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.'; }
}
?>When the form it submitted the php uploads it to the directory “$directory”. The function !feof() reads as – before reaching the end of a file. So while it hasn’t reached the end, write to the new directory and stop once the end is reached. The path to the file is given as “$directory.$filename.”
There u have it!
Popularity: 95% [?]
Filed Under: PHP • Tutorials • Web Programming




Hello, can you please post some more information on this topic? I would like to read more.
I updated the post with more information.
[...] your server. Remaining resize and rename functionalities you have add to script. Check this link http://bgallz.org/62/php-upload-file-from-url/ This is basic idea… __________________ If you feel my post is usefull then click on to give [...]
[...] The Ctrl+V game http://bgallz.org/62/php-upload-file-from-url/ I was posting a link in a programming help thread….. __________________ If you feel my post [...]
I see a lot of good content here, what template do you use ?
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.
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.
Nice post — thanks for sharing.
This helped me to accomplish my job with ease
I like the blog, but could not find how to subscribe to receive the updates by email. Can you please let me know?
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.
Really interesting stuff here. Nice to know about new things for us designers.
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.
[...] Here I showed you how to upload a file from a URL using this function. [...]
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 ..
haha 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!
u r the best!