How to upload a file using PHP

Post Reply
Tony
Lieutenant
Lieutenant
Posts: 86
Joined: Tue Jul 21, 2009 4:11 pm

How to upload a file using PHP

Post by Tony » Sat Nov 28, 2009 6:10 pm

This script will allow you to specify an upload directory, allowed file types, max file size and max space allowed to be used in the upload directory. It will even send you an email letting you know there has been an upload to your website and/or add an entry to a log file for each upload. You need to change the variables at the top of the script as needed.

The specified upload directory can either be a directory relative to the location of the script (in the example the directory "./" is the directory where the script is located, "subdirectory/" would be one directory down from the script) or you can use the full Unix path. Be sure to include a trailing slash on the directory.

If you want to upload files larger than 2MB there are changes required to the php.ini file.

Code: Select all

<?php
/*
This script can send an email and/or make an entry in a log file
There are two variables below - one for an email address and one for a log file
Set both variables to the values you want to use
If you do not want either an email or log entry, comment out the respective line
For example, if you do not want an email sent, put a // in front of the $emailAddress line - same for the $logFile line
*/
$logFile = $_SERVER['DOCUMENT_ROOT'].'/upload.log';   // full path to your log file
$emailaddress = "[email protected]";
$home_page = "home.htm";  // used for a link to return
$uploaddir = "./";  // the directory where files are to be uploaded - include the trailing slash
$fileTypeArray = array(".jpg",".gif",".txt");  // enter in all lower case, the script will handle a match with upper case
$maxSize = 100000;  // maximum file size that can be uploaded - in bytes
$maxFileSpace = 50000000;  // maximum space that can be used by files matching the $fileTypeArray array in the upload directory - in bytes
putenv('TZ=EST5EDT'); // eastern time
// change nothing below this line
$maxDisplay = $maxSize / 1000;
?>
<html><head></head><body>
<div style="text-align: center; margin: 100px auto; border: 1px black solid; width:400px;">
<?php
// print_r($_FILES);  // can be used for debugging
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp_name = $_FILES['file']['tmp_name'];
if (!empty($file_name)) {
  unset($error);
  echo "<br>File Name: $file_name<br><br>"; 
  echo "File Size: $file_size bytes<br><br>";
  // file size test
  if ($file_size == 0 ) $error .= "<span style='color: red;'>Invalid file</span><br>";
  if ($file_size > $maxSize ) $error .= "<span style='color: red;'>Your file exceeds $maxDisplay K.</span><br>";
  // file type test
  if (!in_array(strtolower(strrchr($file_name,'.')),$fileTypeArray) ) $error .= "<span style='color: red;'>Your file is not a valid file type.</span><br>";
  // max directory size test
  foreach(scandir($uploaddir) as $file_select) if (in_array(strtolower(strstr($file_select,'.')),$fileTypeArray)) $total_size = $total_size + filesize($uploaddir.$file_select);
  if (($total_size + $file_size) >= $maxFileSpace)  $error .= "<span style='color: red;'>Total file space limits have been exceeded.</span><br>";
  // scrub characters in the file name
  $file_name = stripslashes($file_name);
  $file_name = preg_replace("#[ ]#","_",$file_name);  // change spaces to underscore
  $file_name = preg_replace('#[^()\.\-,\w]#','_',$file_name);  //only parenthesis, underscore, letters, numbers, comma, hyphen, period - others to underscore
  $file_name = preg_replace('#(_)+#','_',$file_name);  //eliminate duplicate underscore
  // check for file already exists
  if (file_exists($uploaddir.$file_name)) $error .= "<span style='color: red;'>File already exists.</span><br>";
  // if all is valid, do the upload
  if (empty($error)) {
    if (move_uploaded_file($file_tmp_name,$uploaddir.$file_name)) {
      chmod($uploaddir.$file_name,0644);
      echo "<span style='color: green;'>Your file was successfully uploaded!</span>";
      if (isset($emailAddress)) {
        $message = $file_name . " was uploaded by".$_SERVER['REMOTE_ADDR']."at".date('Y-m-d H:i:s'); 
        mail($emailaddress,"You have a file upload",$message,"From: Website <>");
      }
      if (isset($logFile)) {
        $logData = $file_name."||".$_SERVER['REMOTE_ADDR']."||".date('Y-m-d H:i:s')."\r\n";
        @file_put_contents($logFile,$logData,FILE_APPEND|LOCK_EX);
      } 
    } else {
      echo "<span style='color: red;'>Your file could not be uploaded.</span>";
    }
  }
  echo "$error<hr>";
}
?>
<p>Upload a <span style="color: blue;">
<?php
foreach($fileTypeArray as $fileType) echo $fileType;
?>
</span> file to our server<br>
Maximum file size is <?php echo $maxDisplay; ?>K</p>
<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="post" enctype="multipart/form-data">
File: <input type="file" name="file" style="width: 250px;"><br>
<input type="submit" name="submit" value="Upload File"></form>
<a href="<?php echo $home_page; ?>">Return to the Home Page</a>
</div></body></html>
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

Re: How to upload a file using PHP

Post by Neo » Thu Jan 07, 2010 11:01 pm

Another good upload script found on the net.

Code: Select all

<?php
error_reporting(7);

// Max size PER file in KB. example 10MB
$max_file_size="10000";

// Max size for all files COMBINED in KB. example 10MB
$max_combined_size="10000";

//How many file uploads do you want to allow at a time? example: 18.
$file_uploads="18";

//do not edit this.
$websitename="";

// Use random file names? true=yes (recommended), false=use original file name. Random names will help prevent overwritting of existing files!
$random_name=false;

// Please keep the array structure.
$allow_types=array("exe","jpg","gif","png","zip","rar","txt","doc","docx","nfo","bmp","7z","xls","sql","bmp","xml","html","php","htm","xhtml","sos");

// Path to files folder. If this fails use $fullpath below. With trailing slash, CHMOD this dir to 0777!!
$folder="./files/";

// Full url to where files are stored. With Trailing Slash
$full_url="http://mysite.com/files/";

// Only use this variable if you wish to use full server paths. Otherwise leave this empty! With trailing slash
$fullpath="";

//Use this only if you want to password protect your uploads.
$password="";

/*
//================================================================================
* ! ATTENTION !
//================================================================================
: Don't edit below this line unless you know some php. Editing some variables or other stuff could cause undeseriable results!!
*/

// MD5 the password.. why not?
$password_md5=md5($password);

// If you set a password this is how they get verified!
If($password) {
    If($_POST['verify_password']==true) {
        If(md5($_POST['check_password'])==$password_md5) {
            setcookie("phUploader",$password_md5,time()+86400);
            sleep(1); //seems to help some people.
            header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
            exit;
            
        }
    }
}

// The password form, if you set a password and the user has not entered it this will show.
$password_form="";
If($password) {
    If($_COOKIE['phUploader']!=$password_md5) {
        $password_form="<form method=\"POST\" action=\"".$_SERVER['PHP_SELF']."\">\n";
        $password_form.="<table align=\"center\" class=\"table\">\n";
        $password_form.="<tr>\n";
        $password_form.="<td width=\"100%\" class=\"table_header\" colspan=\"2\">Password Required</td>\n";
        $password_form.="</tr>\n";
        $password_form.="<tr>\n";
        $password_form.="<td width=\"35%\" class=\"table_body\">Enter Password:</td>\n";
        $password_form.="<td width=\"65%\" class=\"table_body\"><input type=\"password\" name=\"check_password\" /></td>\n";
        $password_form.="</tr>\n";
        $password_form.="<td colspan=\"2\" align=\"center\" class=\"table_body\">\n";
        $password_form.="<input type=\"hidden\" name=\"verify_password\" value=\"true\">\n";
        $password_form.="<input type=\"submit\" value=\" Verify Password \" />\n";
        $password_form.="</td>\n";
        $password_form.="</tr>\n";
        $password_form.="</table>\n";
        $password_form.="</form>\n";
    }
}

// Function to get the extension a file.
function get_ext($key) {
    $key=strtolower(substr(strrchr($key, "."), 1));
    // Cause there the same right?
    $key=str_replace("jpeg","jpg",$key);
    return $key;
}

$ext_count=count($allow_types);
$i=0;
foreach($allow_types AS $extension) {
    
    //Gets rid of the last comma for display purpose..
    
    If($i <= $ext_count-2) {
        $types .="*.".$extension.", ";
    } Else {
        $types .="*.".$extension;
    }
    $i++;
}
unset($i,$ext_count); // why not

$error="";
$display_message="";
$uploaded==false;

// Dont allow post if $password_form has been populated
If($_POST['submit']==true AND !$password_form) {

    For($i=0; $i <= $file_uploads-1; $i++) {
                    
        If($_FILES['file']['name'][$i]) {
                        
            $ext=get_ext($_FILES['file']['name'][$i]);
            $size=$_FILES['file']['size'][$i];
            $max_bytes=$max_file_size*1024;
            
            // For random names
            If($random_name){
                $file_name[$i]=time()+rand(0,100000).".".$ext;
            } Else {
                $file_name[$i]=$_FILES['file']['name'][$i];
            }
            
            //Check if the file type uploaded is a valid file type.
                        
            If(!in_array($ext, $allow_types)) {
                            
                $error.= "Invalid extension for your file: ".$_FILES['file']['name'][$i].", only ".$types." are allowed.<br />Your file(s) were <b>not</b> uploaded.<br />";
                            
                //Check the size of each file
                            
            } Elseif($size > $max_bytes) {
                
                $error.= "Your file: ".$_FILES['file']['name'][$i]." is to big. Max file size is ".$max_file_size."kb.<br />Your file(s) were <b>not</b> uploaded.<br />";
                
                // Check if the file already exists on the server..
            } Elseif(file_exists($folder.$file_name[$i])) {
                
                $error.= "The file: ".$_FILES['file']['name'][$i]." exists on this server, please rename your file.<br />Your file(s) were <b>not</b> uploaded.<br />";
                
            }
                        
        } // If Files
    
    } // For
    
    //Tally the size of all the files uploaded, check if it's over the ammount.
                
    $total_size=array_sum($_FILES['file']['size']);
                  
    $max_combined_bytes=$max_combined_size*1024;
                
    If($total_size > $max_combined_bytes) {
        $error.="The max size allowed for all your files combined is ".$max_combined_size."kb<br />";
    }
        
    
    // If there was an error take notes here!
    
    If($error) {
        
        $display_message=$error;
        
    } Else {
        
        // No errors so lets do some uploading!
        
        For($i=0; $i <= $file_uploads-1; $i++) {
                
            If($_FILES['file']['name'][$i]) {
                
                If(@move_uploaded_file($_FILES['file']['tmp_name'][$i],$folder.$file_name[$i])) {
                    $uploaded=true;
                } Else {
                    $display_message.="Couldn't copy ".$file_name[$i]." to server, please make sure ".$folder." is chmod 777 and the path is correct.\n";
                }
            }
                
        } //For
        
    } // Else
    
} // $_POST AND !$password_form

/*
//================================================================================
* Start the form layout
//================================================================================
:- Please know what your doing before editing below. Sorry for the stop and start php.. people requested that I use only html for the form..
*/
?>



<?php
If($password_form) {
    
    Echo $password_form;
    
} Elseif($uploaded==true) {?>

<style type="text/css">
<!--
a:link {
    color: #000000;
}
a:visited {
    color: #000000;
}
a:hover {
    color: #3399FF;
}
.style1 {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-style: italic;
    font-weight: bold;
    font-size: 10px;
}
-->
</style>
&nbsp;
<table align="center"class="table">

    <tr>
        <td class="table_header" colspan="2"><b>Your file(s) have been uploaded!</b> </td>
    </tr>
    <tr>
    <td class="table_body">
    <br />
<?php
For($i=0; $i <= $file_uploads-1; $i++) {
    
    If($_FILES['file']['name'][$i]) {
        $file=$i+1;
        
                Echo("<b>File #".$file.":</b> <a href=\"".$full_url.$file_name[$i]."\" target=\"_blank\">".$full_url.$file_name[$i]."</a><br /><br />\n");
    }
                
}

?>
<br />
<a href="<?=$_SERVER['PHP_SELF'];?>">Go Back</a>
<br />
</td>
</tr>
</table> 
<?} Else {?>

<?If($display_message){?>
    <div align="center" class="error_message"><?=$display_message;?></div>
    <br />
<?}?>

<form action="<?=$_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data" name="phuploader">
<table align="center"class="table">

    <tr>
        <td class="table_header" colspan="2"><b><?=$websitename;?></b> </td>
    </tr>
    <tr>
        <td colspan="2" class="upload_info">
            <p><b>Allowed Types:</b>
                <?=$types?>
              <br />
              <b>Max size per file:</b> 10 MB </p>
            <p>&nbsp;</p></td>
    </tr>
    <?For($i=0;$i <= $file_uploads-1;$i++) {?>
        <tr>
            <td class="table_body" width="20%"><b>Select File:</b> </td>
            <td class="table_body" width="80%"><input type="file" name="file[]" size="30" /></td>
        </tr>
    <?}?>
    <tr>
        <td colspan="2" align="center" class="table_header">
            <input type="hidden" name="submit" value="true" />
            <input type="submit" value="  Upload!  " /> &nbsp;
            <input type="reset" name="reset" value=" Reset " />      </td>
    </tr>
</table>
</form>

<?php
}
?>
Post Reply

Return to “PHP & MySQL”