Zend - The PHP Company




File Uploading

Add Code


upload.php  

Type: application
Added by: Annie
Entered: 18/03/2002
Last modified: 03/12/2001
Rating: - (fewer than 3 votes)
Views: 15017
Upload script that can handle multiple uploads with file checking. After uploadprocessing all variables are submitted to another script for further processing (e.g. database)


<?php
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: \
// ::                                                                                                 :: \
// ::                                            UPLOAD                                               :: \
// ::                       Processes uploaded files and shows a short summary.                       :: \
// ::                                                                                                 :: \
// ::                                                                                                 :: \
// :: Files are placed in the UPLOADPATH directory (which defaults to the directory this uploadscript :: \
// :: is in.                                                                                          :: \
// :: After processing of the files other form inputs are passed on to the referring script unless    :: \
// :: the SUBMITTO variable is set.                                                                   :: \
// ::                                                                                                 :: \
// :: Files with extensions in $aForbiddenExt are not allowed (you may change this array to your      :: \
// :: needs). Other filerestrictions (such as filesize or type) are handled from the uploadform.      :: \
// ::                                                                                                 :: \
// :: Global options for the upload can be set by placing the appropriate options in hidden inputs.   :: \
// :: File options must be set as inputs with name 'inputname_OPTION'. For a list of available        :: \
// :: options see below.                                                                              :: \
// :: If a file doesn't meet the criteria it is declined.                                             :: \
// :: Files are renamed to a semi-unique name (number of seconds since the epoch + a countervalue),   :: \
// :: unless the configuration option '_NONUNIQUE' is used for the fileinput. For these files only    :: \
// :: some of the character are replaced to avoid problems with certain browsers (such as spaces      :: \
// :: in filenames)                                                                                   :: \
// ::                                                                                                 :: \
// :: Options for file-inputs:                                                                        :: \
// ::  - _MAXSIZE   : maximum size of the file                                                        :: \
// ::  - _FILETYPE  : comma-separated list of all allowed filetypes                                   :: \
// ::  - _NOUNIQUE  : if 'true' the file won't be renamed to semi-unique value (standard is false)    :: \
// ::  - _IMGWMAX   : image width  (maximum)                                                          :: \
// ::  - _IMGHMAX   : image height (maximum)                                                          :: \
// ::  - _IMGW      : image width  (absolute)                                                         :: \
// ::  - _IMGH      : image height (absolute)                                                         :: \
// ::                                                                                                 :: \
// :: Global configuration options:                                                                   :: \
// ::  - UPLOADPATH : path where uploaded files are moved to                                          :: \
// ::  - MAXSIZE    : maximum size of total upload                                                    :: \
// ::  - FILETYPE   : comma-separated list of all allowed filetypes (total download)                  :: \
// ::  - SUBMITTO   : script to use after the upload is processed                                     :: \
// ::                                                                                                 :: \
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: \

$bUpload true;
$aMessages = array(
     
"<tr><td valign='top' colspan='2'>upload exceeds maximum of %s bytes.</td></tr>"
    
,"- file error.<br />"
    
,"- filesize exceeds maximum of %s bytes.<br />"
    
,"- filetype not allowed.<br />"
    
,"- image exceeds max width of %s px.<br />"
    
,"- image exceeds max height of %s px.<br />"
    
,"- image width is not %s px.<br />"
    
,"- image height is not %s px.<br />"
);
$aImageExt = array("jpg""jpeg""gif""png");
$aForbiddenExt = array("php""so""phtml""shtml""html""htm""js""pl""cgi""vbs");
$sMsg "";
$sFileNameInputs "";

// upload path instellen
if ($_POST["UPLOADPATH"] != "")
{
    
$UPLOADPATH $_SERVER["DOCUMENT_ROOT"];
    
$UPLOADPATH .= $_POST["UPLOADPATH"];
    if (
substr($UPLOADPATH, -1) != "/"$UPLOADPATH .= "/";
}

if (!
is_dir($UPLOADPATH))
{
    
$UPLOADPATH $_SERVER["SCRIPT_FILENAME"];
    
$UPLOADPATH substr($UPLOADPATH0strrpos($UPLOADPATH"/")+1);
}

// determine whether maximum upload size is reached
if ($bUpload && $_POST["MAXSIZE"] != "" && is_numeric($_POST["MAXSIZE"]))
{
    
$iMaxSize = (integer) $_POST["MAXSIZE"];
    
$iCurSize 0;
    foreach(
$_FILES as $key=>$value$iCurSize += $_FILES[$key]['size'];
    if (
$iCurSize $iMaxSize)
    {
        
$bUpload false;
        
$sMsg .= sprintf($aMessages[0], $iMaxSize);
    }
}

// determine whether files meet there criteria
if ($bUpload)
{
    
$iCounter 0;
    foreach(
$_FILES as $key=>$value)
    {
        
$_FILES[$key]['msg'] = "";
        if (
is_uploaded_file($$key))
        {
            
// file-extension
            
$sExt substr(strrchr($_FILES[$key]['name'], "."), 1);
            
            if (
in_array($sExt$aForbiddenExt))
            {
                
$_FILES[$key]['msg'] = $aMessages[1];
            }
            else
            {
                
// check filesize
                
if ($_POST[$key."_MAXSIZE"] && is_numeric($_POST[$key."_MAXSIZE"]))
                {
                    
$iFileSize = (integer) $_FILES[$key]['size'];
                    
$iMaxSize  = (integer) $_POST[$key."_MAXSIZE"];
                    if (
$iFileSize $iMaxSize)
                        
$_FILES[$key]['msg'] .= sprintf($aMessages[2], $iMaxSize);
                }
                
                
// check filetype
                
if ($_POST["FILETYPE"] != "")
                    
$aFileTypes explode(","$_POST["FILETYPE"]);
                else if (
$_POST[$key."_FILETYPE"] != "")
                    
$aFileTypes explode(","$_POST[$key."_FILETYPE"]);
                else
                    
$aFileTypes 0;
                if (
is_array($aFileTypes) && !in_array($sExt$aFileTypes))
                        
$_FILES[$key]['msg'] .= $aMessages[3];
                
                
// for images check their sizes
                
if (in_array($sExt$aImageExt))
                {
                    
// image info
                    
$aImgInfo getImageSize($$key);
                    
                    
// width
                    
if ($_POST[$key."_IMGW"] != "" && is_numeric($_POST[$key."_IMGW"]))
                    {
                        
$iImgAbsW = (integer) $_POST[$key."_IMGW"];
                        if (
$aImgInfo[0] != $iImgAbsW)
                            
$_FILES[$key]['msg'] .= sprintf($aMessages[6], $iImgAbsW);
                    }
                    
// height
                    
if ($_POST[$key."_IMGH"] != "" && is_numeric($_POST[$key."_IMGH"]))
                    {
                        
$iImgAbsH = (integer) $_POST[$key."_IMGH"];
                        if (
$aImgInfo[1] != $iImgAbsH)
                            
$_FILES[$key]['msg'] .= sprintf($aMessages[7], $iImgAbsH);
                    }
                    
                    
// max. width
                    
if ($_POST[$key."_IMGWMAX"] != "" && is_numeric($_POST[$key."_IMGWMAX"]))
                    {
                        
$iImgMaxW = (integer) $_POST[$key."_IMGWMAX"];
                        if (
$aImgInfo[0] > $iImgMaxW)
                            
$_FILES[$key]['msg'] .= sprintf($aMessages[4], $iImgMaxW);
                    }
                    
// max. height
                    
if ($_POST[$key."_IMGHMAX"] != "" && is_numeric($_POST[$key."_IMGHMAX"]))
                    {
                        
$iImgMaxH = (integer) $_POST[$key."_IMGHMAX"];
                        if (
$aImgInfo[1] > $iImgMaxH)
                            
$_FILES[$key]['msg'] .= sprintf($aMessages[5], $iImgMaxH);
                    }
                }
            }
            
            
// file processing
            
if ($_FILES[$key]['msg'] == "")
            {
                
// rename file (disallowed chars) or rename to timestamp
                
if ($_POST[$key "_NOUNIQUE"] == "true")
                    
$sFilename strtr($_FILES[$key]['name'], "',;` %#+""________");
                else
                    
$sFilename time() . $iCounter++ . "." $sExt;

                
// move file
                
if (@move_uploaded_file($$key$UPLOADPATH $sFilename))
                {
                    
$_FILES[$key]['msg'] = "upload completed.<br />";
                    
$sFileNameInputs .= "<textarea name='$key'>{$sFilename}</textarea>";
                }
                else
                {
                    
$_FILES[$key]['msg'] = "move of file failed.<br />";
                }
            }
            
            
$sMsg .= sprintf("<tr><td valign='top'><b>%s</b></td><td valign='top'>%s</td></tr>"
                                
,($_FILES[$key]['name'] ? $_FILES[$key]['name'] : $key)
                                ,
$_FILES[$key]['msg']
                            );
        }
    }
}

// summary
echo "<html><head><title>U P L O A D</title></head><body>";
echo 
"<table border='0' cellpadding='2' cellspacing='4'>";
echo 
"<tr><td><b>file</b></td><td>&nbsp;</td></tr>";
echo (
$sMsg $sMsg "<tr><td colspan=2>no files found</td></tr>");
echo 
"</table>";

// form
if (!$_POST["SUBMITTO"])
{
    
$iQuestionPos strrpos($_SERVER['HTTP_REFERER'], "?");
    
$sReferer substr($_SERVER['HTTP_REFERER']
                        ,
0
                        
,($iQuestionPos $iQuestionPos strlen($_SERVER['HTTP_REFERER'])));
}
else 
$sReferer $_POST["SUBMITTO"];

if (
$sReferer != "")
{
    echo 
"<div style='visibility:hidden'>";
    echo 
"<form action='"$sReferer"?"$_SERVER['QUERY_STRING'], "' method='post'>";
    echo 
$sFileNameInputs;
    foreach(
$_POST as $key=>$value)
    {
        if (
get_magic_quotes_gpc()) $value stripslashes($value);
        echo 
"<textarea name='"$key"'>"$value"</textarea>";
    }
    echo 
"</form>";
    echo 
"<script type='text/javascript'>setTimeout('document.forms[0].submit()',2000);</script>";
    echo 
"</div>";
}
else
{
    echo 
"<p><b>unable to submit form values!</b></p>";
}

echo 
"</body></html>";
?>


Usage Example




Rate This Script





Search



This Category All Categories