Skip to content

Instantly share code, notes, and snippets.

@jsrn
Last active December 15, 2015 17:19
Show Gist options
  • Save jsrn/5295449 to your computer and use it in GitHub Desktop.
Save jsrn/5295449 to your computer and use it in GitHub Desktop.
A short script to handle file upload in php.
<?php
/* * ****************************************************************************
* File uploader script.
* @author jsrn
*
* <form action="uploader.php" method="POST">
* <input type="file" name="file">
* <input type="submit" value="Upload">
* </form>
*/
$allowedExtensions = array('xls', 'xlsx','png');
// Mime type definitions for different extensions.
$allowedMimeTypes = array();
$allowedMimeTypes['xls'] = "application/octet-stream";
$allowedMimeTypes['xlsx'] = "application/octet-stream";
$allowedMimeTypes['png'] = "image/png";
$uploadName = $_FILES['file']['name'];
$filename = $_FILES['file']['tmp_name'];
$filetype = $_FILES['file']['type'];
echo "Uploading file: ", $uploadName, ' with type ', $filetype, '<br>';
// Ensure the file ends with the correct extension
$bits = explode(".", $uploadName);
$extension = array_pop($bits);
if (!in_array($extension, $allowedExtensions)) {
echo "Only " + implode(", ", $allowedExtensions) + " files are permitted.";
die();
}
// Ensure the correct mime type
if ($filetype != $allowedMimeTypes[$extension]) {
echo "Disallowed MIME-type for uploaded file.";
die();
}
echo "Uploading file: $uploadName with type $filetype<br>";
echo "Stored in $filename<br>";
// Do whatever it is you wanted to do with the file.
$filepath = "private/companylogos/";
$uploadedfile = $filepath . basename($uploadName);
if (move_uploaded_file($filename, $uploadfile)) {
echo "File is valid, and was successfully uploaded.<br>";
echo "<a href=$uploadedfile>Get file</a>";
} else {
echo "File uploading failed.<br>";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment