Last active
September 15, 2015 14:28
-
-
Save niksudan/27577466e8a6304ba36e to your computer and use it in GitHub Desktop.
Uploads a file [PHP]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Uploads a file | |
* | |
* @param $_FILES $file | |
* @param string $directory | |
* @param string $filename | |
* @param array $formats | |
* @return string/array filepath/errors | |
*/ | |
function upload_file( $file, $directory = '/uploads', $name = NULL, $formats = NULL ) | |
{ | |
$fullpath = $_SERVER['DOCUMENT_ROOT'].$directory; | |
$errors = array(); | |
// Make directory if doesn't exist | |
if ( !is_dir($fullpath ) ) { | |
if ( !mkdir( $fullpath, 0700 ) ) { | |
array_push( $errors, 'There was a problem uploading to the given directory.' ); | |
} | |
} | |
// Check if filetype is allowed (document) | |
$type = pathinfo( $file['name'], PATHINFO_EXTENSION ); | |
$allowed = $formats != NULL ? in_array( strtolower( $type ), $formats ) : true; | |
if ( $allowed ) { | |
// Set name | |
$name = $name == NULL ? 'upload-' . date('Y-m-d-g-i-s') . '.' . $type : $name . '.' . $type; | |
// Move uploaded file to the directory | |
if ( move_uploaded_file( $file['tmp_name'], $fullpath . '/' . $name ) ) { | |
return $directory . $name; | |
// Problem with moving file | |
} else { | |
array_push( $errors, 'There was a problem processing your file.' ); | |
} | |
// Invalid filetype | |
} elseif ( $formats != NULL ) { | |
array_push( $errors, 'Your file must be one of the following types: '.implode( ', ', $formats ) ); | |
} | |
return $errors; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment