Home » Code, PHP Functions, Tutorials

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:

<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 “downloads” with the random number and the file’s name. This is done with writing permissions so that we can write the data from the url file to this one.

$newfile = fopen("./downloads/" . $rand . basename($url), "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


// 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(10000,99999);
$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:<br/>';
echo '<a href="'.$directory.$filename.'" target="_blank">'.$directory.$filename.'</a>';

}
} else { echo 'Could not establish new file ('.$downloads.$rand.basename($url).') 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!

5

Popularity: 95% [?]

Share/Bookmark this!

14 Comments

Leave a reply

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally recognized avatar, please register at Gravatar.

Side Notes

This entry was posted by on April 26, 2009 at 12:27 PM and filed under Code, PHP Functions, Tutorials category.

You can add your comments or trackback from your own site. To keep you updated to the latest discussion, you can subscribe to these comments via RSS.

Recent Entries

Pages

Recent Comments

Resources

Questions & Answers

Just started! Have not answered any questions.

Tag Cloud

background body CSS database date dropdown email error_reporting favicon file filesize form format function global hosting HTML image Javascript limit link linkbar mysql numbers online option ordinalize pagination pattern photoshop PHP resize rows script search snowing stylesheet switch table thumbnail time timestamp upload validate variables

Sponsors