Skip to content

Instantly share code, notes, and snippets.

@gaffling
Last active February 12, 2020 14:13
Show Gist options
  • Save gaffling/7b1a9d2e48c230e8984732a68504b18d to your computer and use it in GitHub Desktop.
Save gaffling/7b1a9d2e48c230e8984732a68504b18d to your computer and use it in GitHub Desktop.
[File Upload] HTML Form and Upload Script #php #upload #materialize
<?php
/* ------------------------------------------------------------------------ */
/* [File Upload] HTML Form and Upload Script #function #upload #materialize */
/* ------------------------------------------------------------------------ */
$id = '4711'; // SETUP ID of the Upload Record
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
<link rel="stylesheet" href="https://www.adilbo.com/tracker/tpl/css/font.css?v2.0">
<link type="text/css" rel="stylesheet" href="https://www.adilbo.com/tracker/tpl/css/materialize.min.css">
</head>
<body>
<div class="container">
<div class="badge grey lighten-3 hoverable noprint" style="padding:1em">
<form action="upload.php?id=<?php echo $id; ?>" method="post" enctype="multipart/form-data" target="result" onsubmit="setTimeout(function(){window.location.reload();},3000)">
<div class="row">
<div class="file-field input-field">
<?php /* Get all Files that start with that ID before an underscore '_' */ $file = glob('data/'.$id."_*.*"); if ( count($file) < 1) {
/* NO UPLOADED FILES AVAILABLE YET */ ?>
<!-- SELECT UPLOAD -->
<div class="black btn waves-effect waves-light" title="SELECT UPLOAD">
<icon add inverse></icon>
<input type="file" accept="<?php echo rtrim('.'.implode(',.',$UPLOAD_ALLOWED_FILE_TYPES),',.'); ?>" name="fileToUpload" onchange="document.getElementById('filename').value=this.value.replace('C:\\fakepath\\', '');">
</div>
<!-- INFO IF NO FILE EXISTS -->
<div class="file-path-wrapper" style="float:left;padding-right:5px;">
<input id="filename" type="text" class="file-path" readonly placeholder="Select Upload...">
</div>
<!-- UPLOAD -->
<button title="UPLOAD" class="black btn waves-effect waves-light" type="submit" name="submit"><icon style="transform:rotate(-90deg);" logout inverse></icon></button>
<?php } ?>
<?php if ( count($file) > 0) { /* FILES HAVE ALREADY BEEN UPLOADED */ ?>
<!-- DELETE -->
<button style="margin-right:5px;" title="DELETE" onclick="return confirm('Are you sure?');" class="white btn waves-effect waves-light" type="submit" name="delete" ><icon del></icon></button>
<!-- SELECT UPLOAD -->
<div class="black btn waves-effect waves-light" title="SELECT UPLOAD">
<icon add inverse></icon>
<input type="file" accept="<?php echo rtrim('.'.implode(',.',$UPLOAD_ALLOWED_FILE_TYPES),',.'); ?>" name="fileToUpload" onchange="document.getElementById('select').innerHTML='<input style=&quot;margin:0 5px&quot; type=&quot;text&quot; class=&quot;file-path&quot; readonly value=&quot;'+this.value.replace('C:\\fakepath\\', '')+'&quot;>';">
</div>
<!-- SELECT DOWNLOAD -->
<div id="select" style="float:left;padding:0 5px;">
<select name="archivedFile" id="download" title="SELECT DOWNLOAD">
<option value="">Select Download...</option>
<?php foreach($file as $name){$view=explode('_',$name,2);echo'<option value="'.$name.'">'.$view[1].'</option>';} ?>
</select>
</div>
<!-- UPLOAD -->
<button style="margin-bottom:5px" title="UPLOAD" class="black btn waves-effect waves-light" type="submit" name="submit"><icon style="transform:rotate(-90deg);" logout inverse></icon></button>
<!-- DOWNLOAD -->
<?php /* Build URL of Script without Filename */
$url=(isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']=='on'?'https://':'http://').$_SERVER['HTTP_HOST'].dirname(htmlspecialchars($_SERVER['PHP_SELF']));
?>
<button title="DOWNLOAD" style="float:left;margin-left:5px;margin-bottom:5px" class="black btn waves-effect waves-light" onClick="if(document.getElementById('download').options[document.getElementById('download').selectedIndex].value!=''){window.location='<?php echo $url; ?>'+document.getElementById('download').options[document.getElementById('download').selectedIndex].value;}"><icon save inverse></icon></button>
<?php } ?>
<iframe name="result" style="width:100%" height="65" frameBorder="0"></iframe>
</div>
</div>
</form>
</div>
</div>
<script src="https://www.adilbo.com/tracker/tpl/js/jquery-2.1.1.min.js"></script>
<script src="https://www.adilbo.com/tracker/tpl/js/materialize.min.js"></script>
<script> $(document).ready(function(){ $('select').formSelect(); }); </script>
</body>
</html>
<?php
/* ------------------------------------------------------------------------ */
/* [File Upload] HTML Form and Upload Script #function #upload #materialize */
/* ------------------------------------------------------------------------ */
// define all allowed file types (NEVER ALLOW json)
$UPLOAD_ALLOWED_FILE_TYPES = array(
'jpg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', /* IMAGES */
'doc', 'rtf', 'txt', 'docx', 'pdf', /* TEXT */
'mp3', 'mp4', 'wav', 'mpg', /* MEDIA */
'xls', 'csv', 'xlsx', /* TABLE */
'zip', 'rar', /* ARCHIV */
);
// define max. File Size in MB for one upload file
$UPLOAD_MAX_FILE_SIZE_ADMIN = 5; // in MB
// ini frame output
$INI_FRAME_OUTPUT = '<body style="background-color:#eee;padding:7px;margin:0;"><tt><small>';
if(isset($_POST["delete"])) { // delete the given file
echo $INI_FRAME_OUTPUT;
$DELETE_FILE = explode('_', basename($_POST['archivedFile']), 2);
if (unlink($_POST['archivedFile']) )
die('File is deleted: '.$DELETE_FILE[1]);
else die('No File to deleted!');
} else if ( isset($_POST["submit"]) ) { // Only if the Form is send
echo $INI_FRAME_OUTPUT;
$UPLOAD_FILE = 'data/' . @$_GET['id'].'_'.basename($_FILES["fileToUpload"]["name"]); // Build File Name with Path
$UPLOAD_OK = 1; // INI Var
$UPLOAD_FILE_TYPE = strtolower(pathinfo($UPLOAD_FILE, PATHINFO_EXTENSION)); // Get File Type from Extention
if (basename($_FILES["fileToUpload"]["name"]) == '') { // Check if a file was selected
die("No File selected.<br>");
}
$CHECK_IF_IMAGE = getimagesize($_FILES["fileToUpload"]["tmp_name"]); // Check if image file is a actual image or not
if($CHECK_IF_IMAGE !== false) {
echo "File is an " . $CHECK_IF_IMAGE["mime"] . ".<br>";
$UPLOAD_OK = 1;
} else {
echo "File is not an image.<br>";
$UPLOAD_OK = 1;
}
if (file_exists($UPLOAD_FILE)) { // Check if file already exists
echo "Sorry, file already exists.<br>";
$UPLOAD_OK = 0;
}
// Check max ADMIN file size
$UPLOAD_MAX_FILE_SIZE_SYSTEM = min(ini_get('post_max_size'), ini_get('upload_max_filesize'));
$UPLOAD_MAX_FILE_SIZE_SYSTEM = str_replace('M', '', $UPLOAD_MAX_FILE_SIZE_SYSTEM);
if (round(($_FILES["fileToUpload"]["size"] / 1025 / 1025 ) ,4) > $UPLOAD_MAX_FILE_SIZE_ADMIN ) { // 'MB'
echo "Sorry, your file is too large (max. " .$UPLOAD_MAX_FILE_SIZE_ADMIN. " MB) for the Admin.<br>";
$UPLOAD_OK = 0;
// Check max SYSTEM file size
}else if (round(($_FILES["fileToUpload"]["size"] / 1025 / 1025), 4) > $UPLOAD_MAX_FILE_SIZE_SYSTEM ) { // 'MB'
echo "Sorry, your file is too large (max. " .$UPLOAD_MAX_FILE_SIZE_SYSTEM. " MB) for the System.<br>";
$UPLOAD_OK = 0;
}
if( !in_array($UPLOAD_FILE_TYPE, $UPLOAD_ALLOWED_FILE_TYPES) ) { // Allow certain file formats
echo "Sorry, only special files are allowed: <small>".rtrim(implode(', ', $UPLOAD_ALLOWED_FILE_TYPES), ', ')."</small><br>";
$UPLOAD_OK = 0;
}
if ($UPLOAD_OK == 0) { // Check if $UPLOAD_OK is set to 0 by an error
echo "Sorry, your file was not uploaded.<br>";
} else { // If everything is ok, try to upload file
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $UPLOAD_FILE)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.<br>";
} else {
echo "Sorry, there was an error uploading your file.<br>".$_FILES['fileToUpload']['error'];
}
}
}else{
header('HTTP/1.0 404 Not Found', true, 404);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment