Skip to content

Instantly share code, notes, and snippets.

@akingdom
Last active March 28, 2022 08:52
Show Gist options
  • Save akingdom/6d1478d58155761f9d9356a3cb0569fb to your computer and use it in GitHub Desktop.
Save akingdom/6d1478d58155761f9d9356a3cb0569fb to your computer and use it in GitHub Desktop.
<?php
// An example of receiving file(s) POSTed by an HTML web form (PHP language)
//
// Please add any necessary path and file handling, security, etc. that you require.
//
// By Andrew Kingdom
// MIT license
//
// Uncomment to show errors for debugging:
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
//error_reporting(E_ALL);
session_start();
$message = 'Unprocessed';
$uploadDirname = './uploads';
$allowedFileExtensions = array('jpg', 'jpeg', 'gif', 'png', 'zip', 'txt', 'xls', 'doc', 'pdf');
$allowedFileSize = max_upload_size();
$errors = [];
// echo __FILE__ . "<br>" . PHP_EOL;
// echo dirname(__FILE__) . "<br>" . PHP_EOL;
// echo realpath(dirname(__FILE__)."/..") . "<br>" . PHP_EOL;
$uploadPath = realpath(dirname(__FILE__)."/$uploadDirname").'/';
// echo $uploadPath . "<br>" . PHP_EOL;
// echo glob($_SERVER["DOCUMENT_ROOT"].$dest_path).'<BR>'.PHP_EOL;
$processUserName = posix_getpwuid(posix_geteuid())['name']; // this user needs write access to destination folder
// echo $processUserName . '<BR>';
function max_upload_size() {
$max_size = PHP_INT_MAX;
$post_overhead = 2048; // Reserve 2k for non-file data in the POST.
$tmp = shorthand_bytes(ini_get('upload_max_filesize'));
if ($tmp > 0 && $tmp < $max_size) $max_size = $tmp;
$tmp = shorthand_bytes(ini_get('post_max_size'));
if ($tmp > 0 && $tmp < $max_size) $max_size = $tmp;
$tmp = shorthand_bytes(ini_get('memory_limit'));
if ($tmp > 0 && $tmp < $max_size) $max_size = $tmp;
if ($max_size === PHP_INT_MAX) $max_size = 0; // no upload limit, use 0, for safety -- comment line out if not required.
return $max_size;
}
function shorthand_bytes($str) {
$str = trim($str);
$len = strlen($str);
if ($len == 0) return 0;
$last = strtolower($str[$len-1]);
return round(floatval($str) * pow(1024, stripos('bkmgtpezy', $last)));
}
$phpFileUploadErrors = array(
0 => 'There is no error, the file uploaded with success',
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
4 => 'No file was uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk.',
8 => 'A PHP extension stopped the file upload.',
);
$requestMethod = $_SERVER['REQUEST_METHOD'];
if ($requestMethod !== 'POST') {
$errors[] = "Server request method is $requestMethod, not POST";
} else {
$filecount = 0;
foreach($_FILES as $file){
$filecount += 1;
}
if ($filecount === 0) {
$errors[] = 'No files were included to post. Check if it exceeds allowed size and optionally, that <input> has a name';
}
foreach($_FILES as $file){
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_type = $file['type'];
$file_size = $file['size'];
$tmp = explode('.', $file['name']);
$file_ext = strtolower(end($tmp));
$file_sanitized = preg_replace("/[^A-Za-z0-9\.\_\-]/", '_', $file_name);
$newName = $file_sanitized . '-' . md5(time() . $file_name). '.' . $file_ext;
$sanitizedPath = $uploadPath . $newName;
$uploadError = $file['error'];
// Debug the received info...
// echo $file_name . '&nbsp;' . $file_tmp . '&nbsp;' . $file_type . '&nbsp;' . $file_size . '<br>';
// Process the received file...
if (!in_array($file_ext, $allowedFileExtensions)) {
$errors[] = 'Extension not allowed: ' . $file_name . ' ' . $file_type; // .'Allowed file types: ' . implode(',', $allowedfileExtensions);
continue;
}
if ($file_size > $allowedFileSize) {
$errors[] = 'File size exceeds limit (' . $allowedFileSize . '): ' . $file_name . ' ' . $file_type;
continue;
}
if ($uploadError !== 0) {
$errors[] = 'There is some error in the file upload. <br>Please check the following error.<br><span style="color:darkred">Error: ' . $uploadError .' ('.$phpFileUploadErrors[$uploadError].')</span>';
continue;
}
if (!file_exists($file_tmp)) {
$errors[] = "The file <u>$file_tmp</u> was not found to be uploaded.";
// $errors[] = "The uploaded file could not be move to the upload directory. Please make sure the upload directory is writable by web server.";
continue;
}
$moved = move_uploaded_file($file_tmp, $sanitizedPath);
if(!$moved)
{
$errors[] = 'There was some error moving the file to upload directory. Please make sure the upload directory is writable by web server.';
continue;
}
if (!file_exists($sanitizedPath)) {
$errors[] = "The file <u>$sanitizedPath</u> does not exist in its final destination.";
// $errors[] = "The uploaded file could not be move to the upload directory. Please make sure the upload directory is writable by web server.";
continue;
}
// ... add any additional handling here (e.g. add filename and url to database)
}
}
// if ($errors) print_r($errors);
if (!empty($errors)) {
$message = 'Errors occurred:<br>'.implode('<br>', $errors);
} else {
// return 'success' string...
// $message ='File is successfully uploaded.';
$message ='1';
}
// Finally
// Redirect to another page...
// $_SESSION['message'] = $message;
// header("Location: ./index.php");
//-or-
// Return the raw message...
echo $message;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment