Zend - The PHP Company




File Uploading

Add Code


The works -- file upload that's simple and elegant  

Type: code fragment
Added by: quinten
Entered: 23/07/2002
Last modified: 07/12/2001
Rating: - (fewer than 3 votes)
Views: 10771
This is a very simple, working example of a file upload. I provide the php code to handle an arbitrary number of file uploads, and example html code.


> HTML code:
> -----------
> <FORM ENCTYPE="multipart/form-data" ACTION="submit.php" METHOD=POST>
>
> <input type=file name=files[] size=20>
>
> <input type=submit value="Upload File">
>
> </FORM>
>
> submit.php:
> -----------
<?php
>
$path_to_file // enter the directory you want file uploaded to here
>
// file upload code
// it expects the inputs of type file to be named 'files[]'
// it will work with an arbitrarily large number of files
$files $HTTP_POST_FILES['files'];
> if (!
ereg("/$"$path_to_file))
>   
$path_to_file $path_to_file."/";
> foreach (
$files['name'] as $key=>$name) {
>    if (
$files['size'][$key]) {
>       
// clean up file name
>       $name ereg_replace("[^a-z0-9._]""",
>         
str_replace(" ""_",
>             
str_replace("%20""_"strtolower($name)
>             )
>         )
>       );
>       
$location $path_to_file.$name;
>       while (
file_exists($location))
>          
$location .= ".copy";
>       
copy($files['tmp_name'][$key],$location);
>       
unlink($files['tmp_name'][$key]);
//    $content .= "Uploaded File: ".$location."n";
>       $thanks .= "n<br>Successfully uploaded file: $name.";
>    }
> }
> print 
"<h1>File Submission</h1>n";
> print 
$thanks;
>
?>


Usage Example


No example needed really, just plug and chug. You can make it a little friendlier by looking accepting any file name, but to me it makes sense to only accept files with a particular name -- in this case, files[]. Just put as many inputs of type file with name= files[] in your html code as you like, and this script will process them all.

The usual caveats apply. Make sure that your PHP is configured correctly to accept large files if that's the way you swing. I use $HTTP_SERVER_VARS, which is deprecated, but screw me. Fix it if you like. Improve this code. Absolute free use is granted.


Rate This Script





Search



This Category All Categories