Skip to content

Instantly share code, notes, and snippets.

@walterdavis
Last active December 14, 2019 05:16
Show Gist options
  • Save walterdavis/43db422851fae2924e055f50d6a66775 to your computer and use it in GitHub Desktop.
Save walterdavis/43db422851fae2924e055f50d6a66775 to your computer and use it in GitHub Desktop.
Catch a file upload with PHP
<?php
define('FILES_BASE',dirname(__FILE__) . '/_files');
$message = '';
if(isset($_FILES['menu']['name']) && !empty($_FILES['menu']['name'])){
$basename = safe_name(basename($_FILES['menu']['name']));
$ext = strtolower(substr($basename,strrpos($basename,'.') + 1));
$tmpdir = uniqid( 'file_' );
$file_destination_dir = FILES_BASE . '/' . $tmpdir;
$uploadfile = $file_destination_dir . '/' . $basename;
if(in_array($ext,array('pdf', 'txt'))){
mkdir($file_destination_dir);
chmod($file_destination_dir,0775);
if (move_uploaded_file($_FILES['menu']['tmp_name'], $uploadfile)) {
chmod($uploadfile,0664);
$message = 'File uploaded successfully: ' . $uploadfile;
}else{
$message = 'File could not be saved';
}
}else{
$message = 'File format is incorrect';
}
print $message;
exit;
}
/**
* Converts a user-input filename into a URL-safe name.
*
* @param string $strFileName Input filename
* @return string With all pathname unfriendly stuff removed
* @author Walter Lee Davis
*/
function safe_name($strFileName){
$unsafe = "[^a-zA-Z0-9-_\.]";
$strFileName = str_replace(' ', '_',$strFileName);
$file_out = preg_replace($unsafe,'_',$strFileName);
return preg_replace('/_+/',"_",$file_out);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment