I am very much a beginner when it comes to PHP, however, I seemed to have my image uploader working the way I want to with the following code (sourced online). The only issue is I need to rename the files when the user uploads them to something unique like the user/date. I cannot seem to get it working when I alter this code.
I have spent some time searching here and the internet in general but I have struggled to find something that fits.
Please could someone offer me a fix or direct me in the right direction.
Thank You Stack Overflow,
class Uploader {
private $files = array();
private $extensions = array();
private $errors = array();
private $store_directory = "./attachment";
private $resize_image_library_instance = null;
public function __construct($files) {
if (is_array($files) === false) {
$files[] = $files;
}
$this->files = $files;
}
public function set_upload_to($store_directory) {
$this->store_directory = $store_directory;
}
public function set_valid_extensions($extensions, $case_sensitive = false) {
$this->extensions = $extensions;
$this->case_sensitive = $case_sensitive;
}
public function set_resize_image_library($resize_image_library_instance) {
$this->resize_image_library_instance = $resize_image_library_instance;
}
public function is_valid_extension() {
$total = count($this->files);
for($i=0; $i<$total; $i++) {
if (empty($this->files['name'][$i]) === false) {
$file_extension = $this->get_extension($this->files['name'][$i]);
if (in_array($file_extension, $this->extensions) === false) {
$this->errors['type'] = "extension";
$this->errors['file_name'] = $this->files['name'][$i];
$this->errors['file_extension'] = $file_extension;
return false;
}
}
}
return true;
}
public function run() {
$total = count($this->files);
for($i=0; $i<$total; $i++) {
if (empty($this->files['name'][$i]) === false) {
if (move_uploaded_file($this->files['tmp_name'][$i], $this->store_directory.'/'.$this->files['name'][$i]) == false) {
$this->errors['type'] = "run";
$this->errors['file_name'] = $this->files['name'][$i];
}
}
}
return empty($this->errors);
}
public function resize($scale_size = 200) {
$total = count($this->files);
for($i=0; $i<$total; $i++) {
$image = realpath($this->store_directory.'/'.$this->files['name'][$i]);
if (file_exists($image) === true && is_file($image) === true) {
$this->resize_image_library_instance->init($image);
$this->resize_image_library_instance->scale($scale_size);
if ($this->resize_image_library_instance->save($image) === false) {
$this->errors['type'] = "resize";
$this->errors['file_name'] = $image;
}
}
}
return empty($this->errors);
}
public function get_errors() {
return $this->errors;
}
//
private function get_extension($filename) {
$info = pathinfo($filename);
return $info['extension'];
}
private function get_filename($file) {
$info = pathinfo($file);
return $info['filename'];
}
}
To generate an unique name for the uploaded file and save it to server you can use the time(), mt_rand() and then the uploaded file's name together. Like this..
public static function generateUniqueFileName($fileName)
{
return time() . mt_rand(100, 100000) . $fileName;
}
And if you want to pre-pend the username as well then you can pass it to the method and concat it in the beginning.
Related
I am making basic photo hosting, just to upload images and resize them.
Everything works fine, I also have added accept="image/*" for my File upload button, but it is still possible to upload other files. So in my PHP code I check whether it is image or other file, so if it is not image, I basically remove it. But I have a problem. If user uploads "index.php" file, my index file on server will be overwritten and as my code should do, it removes "index.php" so. basically self destruction.
Is there way to restrict file upload before file is actually uploaded on server?
Or at least, is there way to change root directory of file that is
uploaded?
I don't think that JavaScript or HTML restriction will do anything, because "hackermans" can change it easily in inspect element.
class Upload {
private $destinationPath;
private $errorMessage;
private $extensions;
private $allowAll;
private $maxSize;
private $uploadName;
private $seqnence;
private $imageSeq;
public $name = 'Uploader';
public $useTable = false;
function setDir($path) {
$this->destinationPath = $path;
$this->allowAll = false;
}
function allowAllFormats() {
$this->allowAll = true;
}
function setMaxSize($sizeMB) {
$this->maxSize = $sizeMB * (1024 * 1024);
}
function setExtensions($options) {
$this->extensions = $options;
}
function setSameFileName() {
$this->sameFileName = true;
$this->sameName = true;
}
function getExtension($string) {
$ext = "";
try {
$parts = explode(".", $string);
$ext = strtolower($parts[count($parts) - 1]);
} catch (Exception $c) {
$ext = "";
}
return $ext;
}
function setMessage($message) {
$this->errorMessage = $message;
}
function getMessage() {
return $this->errorMessage;
}
function getUploadName() {
return $this->uploadName;
}
function setSequence($seq) {
$this->imageSeq = $seq;
}
function getRandom() {
return strtotime(date('Y-m-d H:i:s')) . rand(1111, 9999) . rand(11, 99) . rand(111, 999);
}
function sameName($true) {
$this->sameName = $true;
}
function uploadFile($fileBrowse) {
$result = false;
$size = $_FILES[$fileBrowse]["size"];
$name = $_FILES[$fileBrowse]["name"];
$ext = $this->getExtension($name);
if (!is_dir($this->destinationPath)) {
$this->setMessage("Destination folder is not a directory ");
} else if (!is_writable($this->destinationPath)) {
$this->setMessage("Destination is not writable !");
} else if (empty($name)) {
$this->setMessage("File not selected ");
} else if ($size > $this->maxSize) {
$this->setMessage("Too large file !");
} else if ($this->allowAll || (!$this->allowAll && in_array($ext, $this->extensions))) {
if ($this->sameName == false) {
$this->uploadName = $this->imageSeq . "-" . substr(md5(rand(1111, 9999)), 0, 8) . $this->getRandom() . rand(1111, 1000) . rand(99, 9999) . "." . $ext;
} else {
$this->uploadName = $name;
}
if (move_uploaded_file($_FILES[$fileBrowse]["tmp_name"], $this->destinationPath . $this->uploadName)) {
$result = true;
} else {
$this->setMessage("Upload failed , try later !");
}
} else {
$this->setMessage("Invalid file format !");
}
return $result;
}
function deleteUploaded() {
unlink($this->destinationPath . $this->uploadName);
}
}
How to use it :
function callMe(){
$uploader = new Upload();
$directory = "NAMEDIR"
if(!is_dir($directory)){
mkdir($directory);
}
$uploader->setDir($directory);
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list//
$uploader->setMaxSize(.5); //set max file size to be allowed in MB//
$uploader->sameName(true);
if($uploader->uploadFile('file')){ //txtFile is the filebrowse element name //
$image = $uploader->getUploadName(); //get uploaded file name, renames on upload//
echo json_encode(array("success"=>true,"message"=>"Success Add","image"=>$directory.$image,"image_upload"=>$image));
}else{//upload failed
echo json_encode(array("success"=>false,"message"=>$uploader->getMessage(),"image"=>""));
}
}
callMe();
What is the best way to inform who use my generator function if something errors occurs, instead of writing weird return or raising exception like this piece of code
function csv_file_generator($csvFilename, $delimiter = ";", $enclousure = '"') {
if(($csvHandler = fopen($csvFilename, 'rb')) === false) {
return;
}
while (($row = fgetcsv($csvHandler, 0, $delimiter, $enclousure)) !== false) {
yield $row;
}
if (feof($csvHandler) === false) {
return;
}
if (fclose($csvHandler) === false) {
return;
}
return; /* Exit Generator */
}
<?php
class CsvFileGenerator {
protected $fp;
protected $delimiter;
protected $enclousure;
public function __construct($filename, $delimiter = ";", $enclousure = '"'){
$this->delimiter=$delimiter;
$this->enclousure=$enclousure;
if(!file_exists($filename)){
throw new Exception("file [$filename] dont exists");
}
if(!is_readable($filename)){
throw new Exception("file [$filename] is not readable");
}
$this->fp = fopen($filename, 'rb');
if($this->fp === false){
throw new Exception("cant open [$filename]");
}
}
public function getGenerator(){
while (($row = fgetcsv($this->fp, 0, $this->delimiter, $this->enclousure)) !== false) {
yield $row;
}
}
public function __destruct() {
if($this->fp){
fclose($this->fp);
}
}
}
foreach( (new CsvFileGenerator('mycsvfile.csv'))->getGenerator() as $line){
#do some
}
One way to rome. :-)
How about callbacks?
function gen($i, $on_close = null, $on_error = null) {
while ($i--) {
yield $i;
if ($i === 5 && is_callable($on_close)) {
$on_close();
}
}
}
$closed = false;
$gen = gen(10, function () use (&$closed) {
$closed = true;
});
foreach ($gen as $x) {
if ($closed) {
break;
}
echo $x, PHP_EOL;
}
I'll admit its not pretty. Another options could be to return instances of special classes to let your main code know something is wrong.
I've got 3 different classes (class Thumbnail in Thumbnail.php, class Upload in Upload.php and class ThumbnailUpload in ThumbnailUpload.php) all in the same namespace (PhotoProject). Currently, it will load an image, create a thumbnail and store both in selected directory, but it will not store the information requested into a database. If you look in the code snippet of blog_insert.php, once it gets to calling $loader->collectFilenames to be assigned to $names, nothing is ever stored in $names[]. I've did a var_dump, and $names is always empty. Any suggestions? Below are the code snippets.
class Upload {
protected $collectednames = [];
protected $typeCheckingOn = true;
protected $notTrusted = ['bin', 'cgi', 'exe', 'js'];
protected $newName;
protected $destination;
protected $max = 8388608;
protected $messages = [];
protected $permitted = [
'image/gif',
'image/png',
'image/jpg'
];
...
public function collectFilenames() {
return $this->collectednames;
}
blog_insert.php
<?php
use PhotoProject\ThumbnailUpload;
require_once '../includes/connection.php';
$conn = dbConnect();
if (isset($_POST['insert'])) {
$OK = false;
$stmt = $conn->stmt_init();
// if a file has been uploaded, process it
if(isset($_POST['upload_new']) && $_FILES['image']['error'] == 0) {
$imageOK = false;
require_once '../PhotoProject/ThumbnailUpload.php';
$loader = new ThumbnailUpload('path to store images');
$loader->setThumbDestination('path to store thumbnail');
$loader->upload();
$names = $loader->collectFilenames();
// $names will be an empty array if the upload failed
if ($names) {
$sql = 'INSERT INTO images (filename, caption) VALUES (?, ?)';
Class Thumbnail
<?php
namespace PhotoProject;
class Thumbnail {
protected $original;
protected $originalwidth;
protected $originalheight;
protected $basename;
protected $thumbwidth;
protected $thumbheight;
protected $maxSize = 350;
protected $canProcess = false;
protected $imageType;
protected $destination;
protected $suffix = '_thb';
protected $messages = [];
public function __construct($image) {
if (is_file($image) && is_readable($image)) {
$details = getimagesize($image);
} else {
$details = null;
$this->messages[] = "Cannot open $image.";
}
// if getimagesize() returns an array, it looks like an image
if (is_array($details)) {
$this->original = $image;
$this->originalwidth = $details[0];
$this->originalheight = $details[1];
$this->basename = pathinfo($image, PATHINFO_FILENAME);
// check the MIME type
$this->checkType($details['mime']);
} else {
$this->messages[] = "$image doesn't appear to be an image.";
}
}
public function setDestination($destination) {
if (is_dir($destination) && is_writable($destination)) {
// get last character
$last = substr($destination, -1);
// add a trailing slash if missing
if ($last == '/' || $last == '\\') {
$this->destination = $destination;
} else {
$this->destination = $destination . DIRECTORY_SEPARATOR;
}
} else {
$this->messages[] = "Cannot write to $destination.";
}
}
public function setMaxSize($size) {
if (is_numeric($size) && $size > 0) {
$this->maxSize = abs($size);
} else {
$this->messages[] = 'The value for setMaxSize() must be a positive number.';
$this->canProcess = false;
}
}
public function setSuffix($suffix) {
if (preg_match('/^\w+$/', $suffix)) {
if (strpos($suffix, '_') !== 0) {
$this->suffix = '_' . $suffix;
} else {
$this->suffix = $suffix;
}
} else {
$this->suffix = '';
}
}
public function create() {
if ($this->canProcess && $this->originalwidth != 0) {
$this->calculateSize($this->originalwidth, $this->originalheight);
$this->createThumbnail();
} elseif ($this->originalwidth == 0) {
$this->messages[] = 'Cannot determine size of ' . $this->original;
}
}
public function getMessages() {
return $this->messages;
}
protected function checkType($mime) {
$mimetypes = ['image/jpeg', 'image/png', 'image/gif'];
if (in_array($mime, $mimetypes)) {
$this->canProcess = true;
// extract the characters after 'image/'
$this->imageType = substr($mime, 6);
}
}
protected function calculateSize($width, $height) {
if ($width <= $this->maxSize && $height <= $this->maxSize) {
$ratio = 1;
} elseif ($width > $height) {
$ratio = $this->maxSize/$width;
} else {
$ratio = $this->maxSize/$height;
}
$this->thumbwidth = round($width * $ratio);
$this->thumbheight = round($height * $ratio);
}
protected function createImageResource() {
if ($this->imageType == 'jpeg') {
return imagecreatefromjpeg($this->original);
} elseif ($this->imageType == 'png') {
return imagecreatefrompng($this->original);
} elseif ($this->imageType == 'gif') {
return imagecreatefromgif($this->original);
}
}
protected function createThumbnail() {
$resource = $this->createImageResource();
$thumb = imagecreatetruecolor($this->thumbwidth, $this->thumbheight);
imagecopyresampled($thumb, $resource, 0, 0, 0, 0, $this->thumbwidth,
$this->thumbheight, $this->originalwidth, $this->originalheight);
$newname = $this->basename . $this->suffix;
if ($this->imageType == 'jpeg') {
$newname .= '.jpg';
$success = imagejpeg($thumb, $this->destination . $newname, 100);
} elseif ($this->imageType == 'png') {
$newname .= '.png';
$success = imagepng($thumb, $this->destination . $newname, 0);
} elseif ($this->imageType == 'gif') {
$newname .= '.gif';
$success = imagegif($thumb, $this->destination . $newname);
}
if ($success) {
$this->messages[] = "$newname created successfully.";
} else {
$this->messages[] = "Couldn't create a thumbnail for " .
basename($this->original);
}
imagedestroy($resource);
imagedestroy($thumb);
}
}
Class ThumbnailUpload
<?php
namespace PhotoProject;
use PhotoProject\Upload;
require_once 'Upload.php';
require_once 'Thumbnail.php';
class ThumbnailUpload extends Upload {
protected $thumbDestination;
protected $deleteOriginal;
protected $suffix = '_thb';
public function __construct($path, $deleteOriginal = false) {
parent::__construct($path);
$this->thumbDestination = $path;
$this->deleteOriginal = $deleteOriginal;
}
/*
** Setter method for the thumbnail destination
*/
public function setThumbDestination($path) {
if (!is_dir($path) || !is_writable($path)) {
throw new \Exception("$path must be a valid, writable directory.");
}
$this->thumbDestination = $path;
}
public function setThumbSuffix($suffix) {
if (preg_match('/\w+/', $suffix)) {
if (strpos($suffix, '_') !== 0) {
$this->suffix = '_' . $suffix;
} else {
$this->suffix = $suffix;
}
} else {
$this->suffix = '';
}
}
public function allowAllTypes() {
$this->typeCheckingOn = true;
}
protected function createThumbnail($image) {
$thumb = new Thumbnail($image);
$thumb->setDestination($this->thumbDestination);
$thumb->setSuffix($this->suffix);
$thumb->create();
$messages = $thumb->getMessages();
$this->messages = array_merge($this->messages, $messages);
}
protected function moveFile($file) {
$filename = isset($this->newName) ? $this->newName : $file['name'];
$success = move_uploaded_file($file['tmp_name'],
$this->destination . $filename);
if ($success) {
// add a message only if the original image is not deleted
if (!$this->deleteOriginal) {
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$result .= ', and was renamed ' . $this->newName;
}
$this->messages[] = $result;
}
// create a thumbnail from the uploaded image
$this->createThumbnail($this->destination . $filename);
// delete the uploaded image if required
if ($this->deleteOriginal) {
unlink($this->destination . $filename);
}
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
}
Class Upload
<?php
namespace PhotoProject;
class Upload {
protected $collectednames = [];
protected $typeCheckingOn = true;
protected $notTrusted = ['bin', 'cgi', 'exe', 'js'];
protected $newName;
protected $renameDuplicates;
protected $destination;
protected $max = 8388608;
protected $messages = [];
protected $permitted = [
'image/gif',
'image/png',
'image/jpg'
];
public function __construct($path) {
if (!is_dir($path) || !is_writable($path)) {
throw new \Exception("$path must be a valid, writable directory.");
}
$this->destination = $path;
}
public function setMaxSize($num) {
if (is_numeric($num) && $num > 0) {
$this->max = (int) $num;
}
}
public function allowAllTypes() {
$this->typeCheckingOn = false;
if (!$suffix) {
$this->suffix = ''; // empty string
}
}
public function upload($renameDuplicates = true) {
$this->renameDuplicates = $renameDuplicates;
$uploaded = current($_FILES);
if (is_array($uploaded['name'])) {
// deal with multiple uploads
foreach ($uploaded['name'] as $key => $value) {
$currentFile['name'] = $uploaded['name'][$key];
$currentFile['type'] = $uploaded['type'][$key];
$currentFile['tmp_name'] = $uploaded['tmp_name'][$key];
$currentFile['error'] = $uploaded['error'][$key];
$currentFile['size'] = $uploaded['size'][$key];
if ($this->checkFile($currentFile)) {
$this->moveFile($currentFile);
}
}
} else {
if ($this->checkFile($uploaded)) {
$this->moveFile($uploaded);
}
}
}
public function getMessages() {
return $this->messages;
}
public function collectFilenames() {
return $this->collectednames;
}
public function getMaxSize() {
return number_format($this->max/1024, 1) . ' KB';
}
protected function checkFile($file) {
$accept = true;
if ($file['error'] != 0) {
$this->getErrorMessage($file);
// stop checking if no file submitted
if ($file['error'] == 4) {
return false;
} else {
$accept = false;
}
}
if (!$this->checkSize($file)) {
$accept = false;
}
if ($this->typeCheckingOn) {
if (!$this->checkType($file)) {
$accept = false;
}
}
if ($accept) {
$this->checkName($file);
}
return $accept;
return true;
}
protected function checkName($file) {
$this->newName = null;
$nospaces = str_replace(' ', '_', $file['name']);
if ($nospaces != $file['name']) {
$this->newName = $nospaces;
}
$extension = pathinfo($nospaces, PATHINFO_EXTENSION);
if (!$this->typeCheckingOn && !empty($this->suffix)) {
if (in_array($extension, $this->notTrusted) || empty($extension)) {
$this->newName = $nospaces . $this->suffix;
}
}
if ($this->renameDuplicates) {
$name = isset($this->newName) ? $this->newName : $file['name'];
$existing = scandir($this->destination);
if (in_array($name, $existing)) {
// rename file
$basename = pathinfo($name, PATHINFO_FILENAME);
$extension = pathinfo($name, PATHINFO_EXTENSION);
$i = 1;
do {
$this->newName = $basename . '_' . $i++;
if (!empty($extension)) {
$this->newName .= ".$extension";
}
} while (in_array($this->newName, $existing));
}
}
}
protected function getErrorMessage($file) {
switch($file['error']) {
case 1:
case 2:
$this->messages[] = $file['name'] . ' is too big: (max: ' .
$this->getMaxSize() . ').';
break;
case 3:
$this->messages[] = $file['name'] . ' was only partially
uploaded.';
break;
case 4:
$this->messages[] = 'No file submitted.';
break;
default:
$this->messages[] = 'Sorry, there was a problem uploading ' .
$file['name'];
break;
}
}
protected function checkSize($file) {
if ($file['error'] == 1 || $file['error'] == 2 ) {
return false;
} elseif ($file['size'] == 0) {
$this->messages[] = $file['name'] . ' is an empty file.';
return false;
} elseif ($file['size'] > $this->max) {
$this->messages[] = $file['name'] . ' exceeds the maximum size
for a file (' . $this->getMaxSize() . ').';
return false;
} else {
return true;
}
}
protected function checkType($file) {
if (in_array($file['type'], $this->permitted)) {
return true;
} else {
if (!empty($file['type'])) {
$this->messages[] = $file['name'] . ' is not permitted type of file.';
return false;
}
}
}
protected function moveFile($file) {
$filename = isset($this->newName) ? $this->newName : $file['name'];
$success = move_uploaded_file($file['tmp_name'],
$this->destination . $filename);
if ($success) {
// add the amended filename to the array of uploaded files
$this->filenames[] = $filename;
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$result .= ', and was renamed ' . $this->newName;
}
$this->messages[] = $result;
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
}
I am attempting to upload multiple files into multiple folders. Unfortunately, with little success.
Any help would be greatly appreciated
I have two form fields:
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max; ?>" />
<input name="menu" type="file" class="input_event noBorder" title="Upload Menu" />
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max; ?>" />
<input name="img" type="file" class="input_event noBorder" title="Upload Img" />
I would like to use one for uploading images, and the other to upload pdf's and/or word docs.
I would also like for these two files to be saved into their corresponding folders (/imgs and /docs).
Some things i have tried
have tried to have two of these, each pointing to the correct path
have tried multiple classes to handle each file
have added array brackets to the input name field (ex: name="menu[]")
I imagine i need to change somethings in the class itself; however i am learning php and this class is cobbled together from 3 books, dozens of Google searches, and a few posts i found here on stack.
Exactly what i need to change is still far beyond me.
Relevant portion of on-page PHP code:
$max = 400000;
if (isset($_POST['submit'])) { //MAIN IF STATEMENT
$destination = './uploads/menus_up/';
try {
$upload = new Upload_File($destination);
$upload->move();
$result = $upload->getMessages();
} catch (Exception $e) {
echo $e->getMessage();
}
Upload class:
class Upload_File {
protected $_uploaded = array();
protected $_destination;
protected $_max = 400000;
protected $_messages = array();
protected $_permitted = array('image/gif',
'image/jpeg',
'image/pjpeg',
'image/png');
protected $_renamed = false;
public function __construct($path) {
if (!is_dir($path) || !is_writable($path)) {
throw new Exception("$path must be a valid, writable directory.");
}
$this->_destination = $path;
$this->_uploaded = $_FILES;
}
public function getMaxSize() {
return number_format($this->_max/1024, 1) . 'kB';
}
public function setMaxSize($num) {
if (!is_numeric($num)) {
throw new Exception("Maximum size must be a number.");
}
$this->_max = (int) $num;
}
public function move($overwrite = false) {
$field = current($this->_uploaded);
if (is_array($field['name'])) {
foreach ($field['name'] as $number => $filename) {
// process multiple upload
$this->_renamed = false;
$this->processFile($filename, $field['error'][$number], $field['size'][$number], $field['type'][$number], $field['tmp_name'][$number], $overwrite);
}
} else {
$this->processFile($field['name'], $field['error'], $field['size'], $field['type'], $field['tmp_name'], $overwrite);
}
}
public function getMessages() {
return $this->_messages;
}
protected function checkError($filename, $error) {
switch ($error) {
case 0:
return true;
case 1:
case 2:
$this->_messages[] = "$filename exceeds maximum size: " . $this->getMaxSize();
return true;
case 3:
$this->_messages[] = "Error uploading $filename. Please try again.";
return false;
case 4:
$this->_messages[] = 'No file selected.';
return false;
default:
$this->_messages[] = "System error uploading $filename. Contact webmaster.";
return false;
}
}
protected function checkSize($filename, $size) {
if ($size == 0) {
return false;
} elseif ($size > $this->_max) {
$this->_messages[] = "$filename exceeds maximum size: " . $this->getMaxSize();
return false;
} else {
return true;
}
}
protected function checkType($filename, $type) {
if (empty($type)) {
return false;
} elseif (!in_array($type, $this->_permitted)) {
$this->_messages[] = "$filename is not a permitted type of file.";
return false;
} else {
return true;
}
}
public function addPermittedTypes($types) {
$types = (array) $types;
$this->isValidMime($types);
$this->_permitted = array_merge($this->_permitted, $types);
}
protected function isValidMime($types) {
$alsoValid = array('image/tiff',
'application/pdf',
'application/msword');
$valid = array_merge($this->_permitted, $alsoValid);
foreach ($types as $type) {
if (!in_array($type, $valid)) {
throw new Exception("$type is not a permitted MIME type");
}
}
}
protected function checkName($name, $overwrite) {
$nospaces = str_replace(' ', '_', $name);
if ($nospaces != $name) {
$this->_renamed = true;
}
if (!$overwrite) {
$existing = scandir($this->_destination);
if (in_array($nospaces, $existing)) {
$dot = strrpos($nospaces, '.');
if ($dot) {
$base = substr($nospaces, 0, $dot);
$extension = substr($nospaces, $dot);
} else {
$base = $nospaces;
$extension = '';
}
$i = 1;
do {
$nospaces = $base . '_' . $i++ . $extension;
} while (in_array($nospaces, $existing));
$this->_renamed = true;
}
}
return $nospaces;
}
protected function processFile($filename, $error, $size, $type, $tmp_name, $overwrite) {
$OK = $this->checkError($filename, $error);
if ($OK) {
$sizeOK = $this->checkSize($filename, $size);
$typeOK = $this->checkType($filename, $type);
if ($sizeOK && $typeOK) {
$name = $this->checkName($filename, $overwrite);
$success = move_uploaded_file($tmp_name, $this->_destination . $name);
if ($success) {
$message = "$filename uploaded successfully";
if ($this->_renamed) {
$message .= " and renamed $name";
}
$this->_messages[] = $message;
} else {
$this->_messages[] = "Could not upload $filename";
}
}
}
}
}//END CLASS....Upload_Menu
Striped down class
protected $_uploaded = array();
protected $_destination;
protected $_max = 400000;
protected $_messages = array();
protected $_permitted = array('image/gif',
'image/jpeg',
'image/pjpeg',
'image/png');
protected $_renamed = false;
public function __construct($path) {
if (!is_dir($path) || !is_writable($path)) {
throw new Exception("$path must be a valid, writable directory.");
}
$this->_destination = $path;
$this->_uploaded = $_FILES;
}
public function move() {
$field = current($this->_uploaded);
$success = move_uploaded_file($field['tmp_name'], $this->_destination . $field['name']);
if ($success) {
$this->_messages[] = $field['name'] . ' uploaded successfully';
} else {
$this->_messages[] = 'Could not upload ' . $field['name'];
}
}
public function getMessages() {
return $this->_messages;
}
I would take a slightly different approach: Send a specific file to the constructor when you create your object like:
$upload = new Upload_File($_FILES['menu'], $destination);
Then you have all the information you need in your class and you don't have to access global variables from within your class.
You can then loop over your $_FILES array to add every file or put that in a different class.
It would require some rewriting in the class but it would make it more flexible and it would meet your needs.
SOLVED
So...for anyone who may come across this in the future, here is a less than elegant, but ultimately effective solution.
pathinfo($string, PATHINFO_EXTENSION) FTW!
I add a sorting mechanism to my processFile method and Wallah!
protected function processFile($filename, $error, $size, $type, $tmp_name, $overwrite) {
$OK = $this->checkError($filename, $error);
if ($OK) {
$sizeOK = $this->checkSize($filename, $size);
$typeOK = $this->checkType($filename, $type);
if ($sizeOK && $typeOK) {
$name = $this->checkName($filename, $overwrite);
/************************ADDED HERE************************************/
if (pathinfo($filename, PATHINFO_EXTENSION) == 'pdf' || 'doc' || 'docx'){
$this->_destination = './uploads/menus_up/';
if (pathinfo($filename, PATHINFO_EXTENSION) == 'png' || 'jpeg' || 'gif'){
$this->_destination = './uploads/eventBG_up/';
/**********************************************************************/
$success = move_uploaded_file($tmp_name, $this->_destination . $name);
if ($success) {
$message = "$filename uploaded successfully";
if ($this->_renamed) {
$message .= " and renamed $name";
}
$this->_messages[] = $message;
} else {
$this->_messages[] = "Could not upload $filename";
}
}
}
}
}
}
I have the following function that I am trying to use to delete a full folder but it does not seem to be deleting any ideas or recommendations?
public function submit()
{
$location = $_SERVER['DOCUMENT_ROOT'].'/_assets/quote/uploads/';
$folderName = $this->quote->getCompanyDetails()->companyName;
$data['companyContact'] = $this->quote->getCompanyDetails()->companyContact;
$this->load->view('submit',$data);
$this->quote->removeQuote();
if(is_dir($location.$folderName) === TRUE)
{
$files = array_diff(scandir($location.$folderName), array('.','..'));
foreach($files as $file)
{
Delete(realpath($location.$folderName).'/'. $file);
}
return rmdir($location.$folderName);
}
else if(is_file($location.$folderName) === TRUE)
{
return unlink($location.$folderName);
}
return FALSE;
}
Update:
public function submit()
{
$location = $_SERVER['DOCUMENT_ROOT'].'/_assets/quote/uploads/';
$folderName = $this->quote->getCompanyDetails()->companyName;
$data['companyContact'] = $this->quote->getCompanyDetails()->companyContact;
$this->load->view('submit',$data);
//$this->quote->removeQuote();
$this->removeFolder();
}
private function removeFolder(){
$location = $_SERVER['DOCUMENT_ROOT'].'/_assets/quote/uploads/';
$folderName = $this->quote->getCompanyDetails()->companyName;
foreach(glob($location.$folderName.'/*') as $file)
{
if(is_dir($location.$folderName))
{
rmdir($location.$folderName);
}else{
unlink($location.$folderName);
}
rmdir($location.$folderName);
}
}
You cannot delete a full folder in one call. You should do it recursively:
function rrmdir($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file))
rrmdir($file);
else
unlink($file);
}
rmdir($dir);
}