- Code: Select all
// function for uploading - input is named "userfile" - by LamiCZE
function upload_file($path, $max_size, $allowed_extension1, $allowed_extension2, $allowed_extension3){
// get temp filename
$tmp = $_FILES['userfile']['tmp_name'];
// get real filename
$file_name = $_FILES['userfile']['name'];
// get file size
$file_size = $_FILES['userfile']['size'];
// use func parameters to construct save path
$place_file = "$path/$file_name";
// get file type according to its extension
$file_type = substr($file_name, -4);
// is extension all right? If true, DOT has to be in the extension
$file_has_extension = strpos($file_type, ".");
// do this if file is grater than func parameter
if($file_size > $max_size){ header("Location: $script_name?post_action=too_big&size=$file_size"); exit(); }
// do if no file selected
if(!is_file($tmp)){ header("Location: $script_name?post_action=no_file"); exit(); }
// do if everything seems OK, but check if DOT is at first place in our extension (for PHP is 0)
if((($file_type == $allowed_extension1) || ($file_type == $allowed_extension2) || ($file_type == $allowed_extension3)) && ($file_has_extension == 0)){
move_uploaded_file($tmp, $place_file);
header("Location: $script_name?post_action=upload_done&filename=$file_name");
// something gets bad with extension...
}else{
// Ooops - we have no extension...
if($file_has_extension === false){ header("Location: $script_name?post_action=no_extension"); exit(); }
// We have extension, but not as expected in func parameters
if($file_has_extension !== false){ header("Location: $script_name?post_action=bad_file&extension=$file_type"); exit(); }
}
}
// **************** end ******************
Example:
- Code: Select all
// dir is "configs", max size 50kB, allowed ext. TAR, RAR, ZIP (some could be empty with "")
upload_file("./configs","50000",".tar",".rar",".zip");
------
Form page header for errors:
- Code: Select all
if($post_action == no_extension){ echo "<H2><font color=\"#FF0000\">Sry, no extension</font></H2>"; }
etc...






