Upload Function

Uploading a file using PHP is not a single step function. To make this easier, I have created a function that will upload a file with just one function call. Just upload('image'); and the file is uploaded! upload() is a function that makes uploading files very easy.

Features

Documentation

Arguments

$file_id
The name of the input field containing the file.
$folder
OPTIONAL - The folder to which the file should be uploaded to - it must be writable.
$types
OPTIONAL - A list of comma(,) separated extensions that can be uploaded. If it is empty, anything goes

Returns

This is somewhat complicated - this function returns an array with two values...

Code


<?php
/**
 * A function for easily uploading files. This function will automatically generate a new 
 *        file name so that files are not overwritten.
 * Taken From: http://www.bin-co.com/php/scripts/upload_function/
 * Arguments:    $file_id- The name of the input field contianing the file.
 *                $folder    - The folder to which the file should be uploaded to - it must be writable. OPTIONAL
 *                $types    - A list of comma(,) seperated extensions that can be uploaded. If it is empty, anything goes OPTIONAL
 * Returns  : This is somewhat complicated - this function returns an array with two values...
 *                The first element is randomly generated filename to which the file was uploaded to.
 *                The second element is the status - if the upload failed, it will be 'Error : Cannot upload the file 'name.txt'.' or something like that
 */
function upload($file_id$folder=""$types="") {
    if(!
$_FILES[$file_id]['name']) return array('','No file specified');

    
$file_title $_FILES[$file_id]['name'];
    
//Get file extension
    
$ext_arr split("\.",basename($file_title));
    
$ext strtolower($ext_arr[count($ext_arr)-1]); //Get the last extension

    //Not really uniqe - but for all practical reasons, it is
    
$uniqer substr(md5(uniqid(rand(),1)),0,5);
    
$file_name $uniqer '_' $file_title;//Get Unique Name

    
$all_types explode(",",strtolower($types));
    if(
$types) {
        if(
in_array($ext,$all_types));
        else {
            
$result "'".$_FILES[$file_id]['name']."' is not a valid file."//Show error if any.
            
return array('',$result);
        }
    }

    
//Where the file must be uploaded to
    
if($folder$folder .= '/';//Add a '/' at the end of the folder
    
$uploadfile $folder $file_name;

    
$result '';
    
//Move the file from the stored location to the new location
    
if (!move_uploaded_file($_FILES[$file_id]['tmp_name'], $uploadfile)) {
        
$result "Cannot upload the file '".$_FILES[$file_id]['name']."'"//Show error if any.
        
if(!file_exists($folder)) {
            
$result .= " : Folder don't exist.";
        } elseif(!
is_writable($folder)) {
            
$result .= " : Folder not writable.";
        } elseif(!
is_writable($uploadfile)) {
            
$result .= " : File not writable.";
        }
        
$file_name '';
        
    } else {
        if(!
$_FILES[$file_id]['size']) { //Check if the file is made
            
@unlink($uploadfile);//Delete the Empty file
            
$file_name '';
            
$result "Empty file found - please use a valid file."//Show the error message
        
} else {
            
chmod($uploadfile,0777);//Make it universally writable.
        
}
    }

    return array(
$file_name,$result);
}

Sample

PHP Part

if($_FILES['image']['name']) {
	list($file,$error) = upload('image','uploads/','jpeg,gif,png');
	if($error) print $error;
}

HTML Part


<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image" /><input type="submit" value="Upload" name="action" />
</form>

Comments

Anonymous at 02 May, 2007 02:36
help me pls..panu ko ba gawin ung download files refresh tapos lalabas na sya sa page
Reply to this.
Anonymous at 09 Jul, 2007 11:27
suba un tavanda beno mi situnda mesqe litovini
Reply to this.
Anonymous at 09 Jul, 2007 11:29
Besimana sodo "upload" una distill mino archive database transfer cono li tada.
Reply to this.
Fhavio at 22 May, 2007 04:57
Great job, this will help a lot
thanks
Reply to this.
cloud_hardcore at 16 Jun, 2007 11:48
i do not understand how to use this function. I'm using dreamweaver..so how can use this upload download function..?

or we must create database after that we can use this function..
i'm using xampp(phpMyAdmin) for the database...

can you anyone tell me step by step how to do...
Reply to this.
Binny V A at 16 Jun, 2007 12:34
This function will run in the server side - you don't need a database for this to work. But sometimes after uploading a file, the file name is inserted into the DB. If you want that, you will have to create the database for that.

PHP already has upload capability - my function just make is a lot more easier.
Reply to this.
Anonymous at 04 Jul, 2007 11:45
Pretty good. How do you add a Browse button to it?
Reply to this.
Crashdaddy at 04 Jul, 2007 12:42
Eureka Springs, I've got it! It uploads the pictures real nice. Now say on that PHP PART you have shown above, where the file actually gets uploaded--what if I wanted to display the picture to show the success. It seems hard to do because of the name change.
Reply to this.
Binny V A at 04 Jul, 2007 10:22
The name will be returned in the array - just use that.
Reply to this.
Anonymous at 07 Jul, 2007 06:08
i would like to use this code in a script i am writing but i plan to copyright the entire thing. can i include this code and give you credit for your section?
Reply to this.
PHPnOOb at 20 Jul, 2007 05:29
I need to access the location and name of the file after it has been saved. How can I go about that? I cannot display the image after it has been uploaded with out being able to call its new name.
Reply to this.
Binny V A at 20 Jul, 2007 10:44
Do something like this...
<?php
list($file,$error) = upload('image','','jpeg,gif,png');
?>

<img src="<?=$file?>" />
Reply to this.
PHPnOOb at 23 Jul, 2007 12:23
Any way to adapt this for use with multiple files with out reusing the whole function?

If the files come in as an array, how can I specify specific variables from the array for use with the function?
Reply to this.
Binny V A at 24 Jul, 2007 12:59
You have to call the function multiple times for that.
Reply to this.
alkaloid at 09 Aug, 2008 06:01
use foreach loop like

foreach($HTTP_POST_FILES as $filename){
upload($file_id, $folder="", $types="")
}

something like that
Reply to this.
PHPnOOb at 23 Jul, 2007 11:17
I need to access the location and name of the file after it has been saved. How can I go about that? I cannot display the image after it has been uploaded with out being able to call its new name.
Reply to this.
Binny V A at 24 Jul, 2007 12:58
You can use the name of the file that is returned by the function for that.
Reply to this.
Anonymous at 01 Aug, 2007 05:24
If i'm using this it is diplay the Undefined Index error for file name.
Reply to this.
Binny V A at 01 Aug, 2007 05:56
Was there an upload error when this happened?
Reply to this.
Kurt at 17 Aug, 2007 12:02
I'm using the PHP functions to upload a PDF to my site. When I open the PDF in my website, everything is ok. However if I delete the file and put another PDF with the same name, I still see the old (not existing) one in my website. If I use an FTP tool to upload the file, it is OK.
Any idea what could be wrong?
Reply to this.
Binny V A at 17 Aug, 2007 07:00
Could be a caching issue - the old file is still cached by the browser. By the way how did you delete the file? Using FTP?
Reply to this.
Kurt at 17 Aug, 2007 10:19
For the delete, I used the php function unlink.
I did some extra testing. On my desktop, It wasn't working, but on my portable it is working just fine both on IE and Firefox. I'll ckeck my desktop again and try to clean the temporary file and so.
Anyway since your function is far better written than what I wrote in a hurry, I'll replace my code by yours. Thanks a lot.
Reply to this.
Snorre at 31 Aug, 2007 02:54
Is there any maximum file size in this script?
Reply to this.
Binny V A at 31 Aug, 2007 10:43
PHP has a default upload limit of 2 MB. If that is increased, this function will use the updated value.
Reply to this.
julie at 30 Nov, 2007 11:36
what code to be added if the file to be uploaded is .doc but it is contain text and image..like a resume..a combination of text and image(picture of the applicant)..and save that file as .doc since it is created in the MS Word..thank you..
Reply to this.
Binny V A at 01 Dec, 2007 04:48
If its a word file, just use this... upload('resume','uploads/','doc')
Reply to this.
Anonymous at 27 Jan, 2008 07:29
now, what would be the names of the files... i am new to php
Reply to this.
Rana at 16 Apr, 2008 01:45
Oh! thats great!
Reply to this.
Hasan at 30 May, 2008 06:31
Thank you for this really handful script, but i have a problem with pdf files. I could'nt figure out what's the problem. When I try to upload a real pdf file it gives "Cannot upload the file 'xx.pdf' : File not writable." . When i change a text file extention to pdf, and upload it, it works. How can i upload pdf files, is there something extra to do ?
Reply to this.
Anonymous at 02 Jun, 2008 07:34
I wonder if your PDFs are exceeding your default file size max (your text file is not likely to do so).
Reply to this.
Hasan at 04 Jun, 2008 04:04
Problem is solved, but i dont know how. I changed default max file size when I trying(Before your replay). I think it requires a system restart, not just apache restart. Thank you.
Reply to this.
Sagy at 02 Nov, 2008 11:53
Heyyy can anybody tell me how to execute the above code.. i am having Model, view and controllers architecture in my PHP code.. can anybody tell me how to execute the above code from the scratch including HTML...because i am new to this field.. ( i want file upload feature in my website )

Reply to this.
Fabio at 25 Feb, 2009 08:32
Hi,

This seems to be a very nice function.

But can we have other inputs besides type=file, I ask this because of enctype in the form tag.

Thank you
Reply to this.
vj at 28 May, 2009 12:28
Hii,

I am wrking with similar thing , but need it to be done in java ... if i try to use get parameter it dorsnt seem to be wrking ... can anyone help me out ..

Thanx in advance
Reply to this.
Comment

Please dont enter you comments in this form - this is a fake form to confuse spamming bots. The next form is the real one.




Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.
Subscribe to Feed