Secure PHP File Upload Script for Word Documents
Classified in Computers
Written on in
English with a size of 3.43 KB
Secure PHP Word Document Upload Script
This PHP script manages secure document uploads, specifically restricting files to the Microsoft Word format, validating file sizes, handling duplicate filenames, and saving the record to a MySQL database.
PHP Upload Code
<?php
// PROGRAMMING BEGINS //::::::::::::::::::::::::::::::: DOCUMENT
if ($success1) {
// define() is a function that defines a constant. Equates to 300KB
define('max_file_size', 3000000);
define('UPLOAD_DIR2', 'documents/');
$file = str_replace(' ', '_', $_FILES['file']['name']);
// Calculate the maximum size of a file to upload
$max = number_format(max_file_size / 2048, 1) . ' KB';
// Define or calculate the file size
$size = number_format($_FILES['file']['size'] / 2048, 1) . ' KB';
// IMPORTANT! TYPE ALLOWED TO UPLOAD THE WORD DOCUMENT
$tipo_permitido = array('application/msword');
$sizeOK = false; // Define if the size is incorrect
$typeOK = false;
// If the file size is correct and is the allowed type of file, then proceed
if ($_FILES['file']['size'] > 0 && $_FILES['file']['size'] <= max_file_size) {
$sizeOK = true;
}
foreach ($tipo_permitido as $type) {
if ($type == $_FILES['file']['type']) {
$typeOK = true;
break;
}
}
if ($sizeOK && $typeOK) {
switch ($_FILES['file']['error']) {
case 0:
$duplicate = true;
$count = 0;
$words = explode('.', $file);
$archivosig = $words[0] . "." . $words[count($words) - 1];
// Code to check if the file exists and handle duplicates
while ($duplicate) {
if (file_exists(UPLOAD_DIR2 . $archivosig)) {
$file = UPLOAD_DIR2 . $archivosig;
$success2 = move_uploaded_file($_FILES['file']['tmp_name'], $file);
$duplicate = false;
} else {
$count++;
$archivosig = $words[0] . "($counter)." . $words[count($words) - 1];
}
}
if ($success2) {
$link = connect();
if ($_SESSION['num'] == 0) {
$extra = 1;
} else {
$extra = 2;
}
} else {
$result = "Unable to upload the document, please try again.";
}
break;
case 3:
$result = "Unable to upload the document, please try again.";
break;
default:
$result = "Problems uploading the document.";
break;
}
} elseif ($_FILES['file']['error'] == 4) {
$result = 'No file selected';
} elseif (!$typeOK) {
$result = "$file has no extension: gif, jpg, png, and neither is it a WORD document";
} else {
$result = "$file cannot be sent. Maximum size: $max.";
}
}
// If both are true, upload to the DB
if ($success1 && $success2) {
$result = mysql_query("INSERT INTO users VALUES ('$login', '$password', '$name', '$level', '$url', '$file')", $link) or die("Connection Failed");
}
header('refresh: 0; url=login.php');
?>