#native_company# #native_desc#
#native_cta#

File uploads made easy Page 2

By Darren Beale
on August 31, 2007

Starting us off, we need to lay down some parameters, for the maximum file size you want to allow the user to upload and – if it’s an image – how high and wide the image can be, else you might get a 1.5MB, 1024 x 768 Jpeg filling up the entire screen!

<?php

$my_max_file_size     "102400";     # in bytes
$image_max_width    "300";     # in pixels
$image_max_height    "300";    # in pixels

?>

Next is the path where the resulting file will sit on your server, this should be absolute and PHP needs ‘write’ permissions to that directory.

<?php

$the_path        "/usr/local/apache/htdocs/sites/dev/phpbuilder/upload/files";

?>

Now, we want to list a number of file-types so we can give sensible error messages later on in the script. This is simply an array indexed by ‘content-types’ with a value that is human readable

<?php

$registered_types = array(
    
"application/x-gzip-compressed"     => ".tar.gz, .tgz",
    
"application/x-zip-compressed"         => ".zip",
    
"application/x-tar"            => ".tar",
    
"text/plain"                => ".html, .php, .txt, .inc (etc)",
    
"image/bmp"                 => ".bmp, .ico",
    
"image/gif"                 => ".gif",
    
"image/pjpeg"                => ".jpg, .jpeg",
    
"image/jpeg"                => ".jpg, .jpeg",
    
"application/x-shockwave-flash"     => ".swf",
    
"application/msword"            => ".doc",
    
"application/vnd.ms-excel"        => ".xls",
    
"application/octet-stream"        => ".exe, .fla (etc)"
); # these are only a few examples, you can add as many as you like

?>

Finally, we want to specify what type of file the user is allowed to upload, for this example, it’s an image that we might want to embed in a web page, so we build up an array of related ‘image’ content-types.

<?php

$allowed_types = array("image/bmp","image/gif","image/pjpeg","image/jpeg");

?>