PHP class for uploading files - php

I'm trying to upload file using this PHP class available at http://www.finalwebsites.com/snippets.php?id=7 (to view the codes for the class http://pastebin.com/sqbMw4sR)
And I've the following codes in the upload processing file
$max_size = 1024*100; // the max. size for uploading
$my_upload = new file_upload;
// upload directory
$my_upload->upload_dir = HOME_PATH."users/";
// allowed extensions
$my_upload->extensions = array(".png", ".jpeg", ".jpg", ".gif");
$my_upload->max_length_filename = 50;
$my_upload->rename_file = true;
$new_name = "testing" . time();
if(isset($Submit)) {
$my_upload->the_temp_file = $_FILES['upload']['tmp_name'];
$my_upload->the_file = $_FILES['upload']['name'];
$my_upload->http_error = $_FILES['upload']['error'];
$my_upload->the_mime_type = $_FILES['upload']['type'];
// because only a checked checkboxes is true
$r = $_POST['replace'];
$my_upload->replace = (isset($r)) ? $r : "n";
// use this boolean to check for a valid filename
$a = $_POST['check'];
$my_upload->do_filename_check = (isset($a)) ? $a : "n";
if ($my_upload->upload($new_name)) {
// new name is an additional filename information,
//use this to rename the uploaded file
$full_path = $my_upload->upload_dir.$my_upload->file_copy;
// just some information about the uploaded file
$info = $my_upload->get_uploaded_file_info($full_path);
// ... or do something like insert the filename to the database
}
}
$error = $my_upload->show_error_string();
According to my understanding, the file should've been uploaded but it neither throws any error nor it is uploaded.
I'm calling this file using ajaxForm (jquery plugin http://malsup.com/jquery/form/#file-upload).
Can anyone please point out what is wrong here?

Here is a new Uploader class
Save the following block as Uploader.php
<?php
class Uploader
{
private $destinationPath;
private $errorMessage;
private $extensions;
private $allowAll;
private $maxSize;
private $uploadName;
private $seqnence;
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);
}
}
?>
Now upload files using Uploader class.
Use following code . Code block is self explanatory .
<?php
$uploader = new Uploader();
$uploader->setDir('uploads/images/');
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list//
$uploader->setMaxSize(.5); //set max file size to be allowed in MB//
if($uploader->uploadFile('txtFile')){ //txtFile is the filebrowse element name //
$image = $uploader->getUploadName(); //get uploaded file name, renames on upload//
}else{//upload failed
$uploader->getMessage(); //get upload error message
}
?>

File uploaded to extension named folder in "upload" folder.
HTML:
<form method="post" action="test_act.php" enctype="multipart/form-data">
<div>
<span>Choose file</span>
<input type="file" name="fileToUpload" id="fileToUpload">
<br/>
<input type="submit" name="fupload" id="fupload">
</div>
</form>
test_act.php (Form Action)
<?php
include ("test_cls.php");
if(isset($_POST['fupload']))
{
$dirpath="upload";
$uploader = new Uploader();
$uploader->setExtensions(array('jpg','jpeg','png','gif','doc','docx')); //allowed extensions list//
$uploader->setMaxSize(1); //set max file size to be allowed in MB//
$uploader->setDir($dirpath);
if($uploader->uploadFile('fileToUpload')) //txtFile is the filebrowse element name //
{
$suc_file = $uploader->getUploadName(); //get uploaded file name, renames on upload//
echo $suc_file." successfully uploaded";
}
else //upload failed
echo $uploader->getMessage(); //get upload error message
}
?>
test_cls.php (class):
<?php
class Uploader
{
private $destinationPath;
private $errorMessage;
private $extensions;
private $maxSize;
private $uploadName;
public $name='Uploader';
function setDir($path){
$this->destinationPath = $path;
}
function setMaxSize($sizeMB){
$this->maxSize = $sizeMB * (1024*1024);
}
function setExtensions($options){
$this->extensions = $options;
}
function setMessage($message){
$this->errorMessage = $message;
}
function getMessage(){
return $this->errorMessage;
}
function getUploadName(){
return $this->uploadName;
}
function uploadFile($fileBrowse){
$result = false;
$size = $_FILES[$fileBrowse]["size"];
$name = $_FILES[$fileBrowse]["name"];
$ext = pathinfo($name,PATHINFO_EXTENSION);
$this->uploadName= $name;
if(empty($name))
{
$this->setMessage("File not selected ");
}
else if($size>$this->maxSize)
{
$this->setMessage("Too large file !");
}
else if(in_array($ext,$this->extensions))
{
if(!is_dir($this->destinationPath))
mkdir($this->destinationPath);
if(!is_dir($this->destinationPath.'/'.$ext))
mkdir($this->destinationPath.'/'.$ext);
if(file_exists($this->destinationPath.'/'.$ext.'/'.$this->uploadName))
$this->setMessage("File already exists. !");
else if(!is_writable($this->destinationPath.'/'.$ext))
$this->setMessage("Destination is not writable !");
else
{
if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.'/'.$ext.'/'.$this->uploadName))
{
$result = true;
}
else
{
$this->setMessage("Upload failed , try later !");
}
}
}
else
{
$this->setMessage("Invalid file format !");
}
return $result;
}
function deleteUploaded($fileBrowse){
$name = $_FILES[$fileBrowse]["name"];
$ext = pathinfo($name,PATHINFO_EXTENSION);
unlink($this->destinationPath.'/'.$ext.'/'.$this->uploadName);
}
}
?>

Related

hello i try to do upload form using (php oop) and i got this error ( Error code: 1) when i upload any video and i don't know how to fix it

I got this problem when I try to do form upload for video using oop PHP (Error code: 1) and I don't know how to fix it
<?php
class VideoProcessor {
private $con;
private $sizeLimit = 500000000;
private $allowedTypes = array("mp4", "flv", "webm", "mkv", "vob", "ogv", "ogg", "avi", "wmv", "mov", "mpeg", "mpg");
public function __construct($con) {
$this->con = $con;
}
public function upload($videoUploadData) {
$targetDir = "uploads/videos/";
$videoData = $videoUploadData->videoDataArray;
$tempFilePath = $targetDir . uniqid() . basename($videoData["name"]);
$tempFilePath = str_replace(" ", "_", $tempFilePath);
$isValidData = $this->processData($videoData, $tempFilePath);
if(!$isValidData) {
return false;
}
if(move_uploaded_file($videoData["tmp_name"], $tempFilePath)) {
echo "File moved successfully";
}
}
private function processData($videoData, $filePath) {
$videoType = pathinfo($filePath, PATHINFO_EXTENSION);
if (!$this->isValidSize($videoData)) {
echo "File too large. Can't be more Than " . $this->sizeLimit . " bytes";
return false;
}
else if(!$this->isValidType($videoType)) {
echo "Invalid file type";
return false;
}
else if($this->hasError($videoData)) {
echo "Error code: " . $videoData["error"];
return false;
}
return true;
}
private function isValidSize($data) {
return $data["size"] <= $this->sizeLimit;
}
private function isValidType($type) {
$lowercased = strtolower($type);
return in_array($lowercased, $this->allowedTypes);
}
private function hasError($data) {
return $data["error"] != 0;
}
}
?>

Restrict ".php" File upload

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();

Image upload with zend framework

I am new to the zend framework. I need to create a user registration with image upload. I have done that. My registration controller and upload controller works. Currently all images are uploading to uploads/user-images/ in public folder. But my actual requirement is, I have to create a specific folder for each user based on their user ID and need to upload their photos to that folder. Also, I need to store that image path in a DB as actualname_current_Timestamp_width_height.extension, but I don't know how to do this. Here I am including my controller codes:
<?php
/**
* PhotoController class file
*
* This file contains a class for PhotoController
*
* #category Zend
* #package Zend_Controller
*
*/
class PhotoController extends Daddara_Controller_BaseController
{
public $session;
function init()
{
parent::init();
$this->view->headScript()->appendFile('/resources/js/upload.js');
$this->view->headScript()->appendFile('/resources/js/jquery.min.js');
$this->view->headScript()->appendFile('/resources/js/jquery.wallform.js');
$this->view->headScript()->appendFile('/resources/js/modernizr.custom.js');
// $this->view->headScript()->appendFile('/resources/js/lightbox/jquery-1.10.2.min.js');
// $this->view->headScript()->appendFile('/resources/js/lightbox/lightbox-2.6.min.js');
}
function indexAction()
{
$this->_forward('upload');
}
/**
* Upload Action action
*
*/
public function uploadAction()
{
$path = "uploads/user-images/";
$shortPath = "uploads/user-images/resize/";
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) {
return "";
}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$em = $this->getEntityManager();
//User Id
$userId = $em->getRepository("Models\User")->findOneBy(array('id' => $this->currentUser->id));
//Registration Id
$registrationId = $em->getRepository("Models\Registration")->findOneBy(array('user' => $this->currentUser->id));
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if($this->getRequest()->isPost()){
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
//echo $ext;exit;
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $ext), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
if($ext=="jpg" || $ext=="jpeg" )
{
$uploadedfile = $path.$actual_image_name;
$src = imagecreatefromjpeg($uploadedfile);
}
else if($ext=="png")
{
$uploadedfile = $path.$actual_image_name;
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=160;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = "uploads/user-images/resize/". $actual_image_name;
imagejpeg($tmp,$filename,100);
$photos = new Models\ProfilePhotos();
$photos->setUser($userId)
->setRegistration($registrationId)
->setPhoto($path.$actual_image_name)
->setShortImage($shortPath.$actual_image_name)
->setAddedOn();
$em->persist($photos);
$em->flush();
echo "<img src='/uploads/user-images/resize/".$actual_image_name."' class='preview'>";
}
else
echo "Fail upload folder with read access.";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
}
}
public function listAction()
{
$em = $this->getEntityManager();
$photo = $em->getRepository('Models\ProfilePhotos')->findBy(array('user' => $this->currentUser->id));
//print_r($image);exit;
$this->view->photo = $photo;
}
/**
* delete function
*/
function deleteAction()
{
$deleteId = $this->getRequest()->getParam('id');
if(empty($deleteId)){
throw new Zend_Controller_Exception("Page not found", 404);
}
$em = $this->getEntityManager();
$del = $em->find("Models\ProfilePhotos", $deleteId);
$em->remove($del);
$em->flush();
$this->addMessage('Data Deleted Successfully "');
$this->_redirect('/photo/list');
}
}
You can create a folder with the command mkdir():
if(mkdir(APPLICATION_PATH . '/public/uploads/' . $userId)){
//dir created
}
You can move a file with copy() and unlink():
if(copy(APPLICATION_PATH . '/public/uploads/' .$filename,
APPLICATION_PATH . '/public/uploads/' .$userId .'/' .$newfilename)) {
unlink(APPLICATION_PATH . '/public/uploads/' . $filename);
}
I have tried something like the following code and thats worked for me. Now i can upload images to a purticular folder for each user based on their user id. Hope this will help someone else.. :-)
$path = "uploads/user-images/";
$em = $this->getEntityManager();
//User Id
$userId = $em->getRepository("Models\User")->findOneBy(array('id' => $this->currentUser->id));
$user_path = "$path".$userId->getId()."/";
if (!file_exists($user_path)) mkdir($user_path, 0777);

Multiple uploads to multiple folders - PHP

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";
}
}
}
}
}
}

How do I modify this to upload multiple files?

My upload code is this. I submit the image to it with postdata. I want to make the file select box accept multiple picutes, and have it work on the backend. I can get the header location to work just fine on my own, but using an array of files has proved to be difficult, even though I've spent hours on stack overflow and google. I'd love it if somebody could show me how to do it.
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$browse = $_POST["browse"];
preg_match('/\.([a-zA-Z]+?)$/', $_FILES['userfile']['name'], $matches);
if(in_array(strtolower($matches[1]), $accepted)) {
if($_FILES['userfile']['size'] <= $maxsize) {
$newname = md5_file($_FILES['userfile']['tmp_name']).'.'.$matches[1];
$browse = $_POST["browse"];
if ($browse == "1") {
$filedir = 'img';
} else if ($browse == "2") {
$filedir = 'zega';
} else if ($browse == "3") {
$filedir = 'noimg';
} else if ($browse == "4") {
$filedir = 'adult';
} else if ($browse == "5") {
$filedir = 'temp';
} else {
$filedir = 'noimg';
}
move_uploaded_file($_FILES['userfile']['tmp_name'], $filedir.'/'.$newname);
$path = $filedir.'/'.$newname;
if (strpos($path,'jpg') !== false){
$img = imagecreatefromjpeg ($path);
imagejpeg ($img, $path, 100);
imagedestroy ($img);
} else if (strpos($path,'gif') !== false){
$img = imagecreatefromgif ($path);
imagegif ($img, $path, 100);
imagedestroy ($img);
} else if (strpos($path,'bmp') !== false){
$img = imagecreatefrombmp ($path);
imagebmp ($img, $path, 100);
imagedestroy ($img);
}
header("Location: index.php?p=uploaded&img=$newname");
} else
header("Location: index.php?p=error&num=2");
} else
header("Location: index.php?p=error&num=1");
}
?>
foreach($_FILES as $key_file=>$file_info){
//your code here instead $_FILES['userfile']['tmp_name'] use $file_info['tmp_name']
}
i wrote a class for uploads sometimes ago.
this class has ability to upload mutiple files at the same time(such as picture .etc).
it also has other ability such as :
-if you upload mutiple files with the same name it will automatically change their name
-you can add permitted types
-set maximum size of uploaded files
...
class Upload {
protected $_uploaded = array();
protected $_destination_upload_folder;
//Constraint
protected $_max_upload_size = 512000;
protected $_permitted_files = array('image/gif', 'image/png', 'image/jpg', 'image/jpeg', 'image/pjpeg');
protected $_error_messages = array();
protected $_renamed_file = false;
public function __construct($input_upload_path) {
if(!is_dir($input_upload_path) || !is_writable($input_upload_path)){
throw new Exception("$input_upload_path must be a valid,writable path!");
}
$this->_destination_upload_folder = $input_upload_path;
$this->_uploaded = $_FILES;
}
protected function checkError($fileName, $error){
switch ($error) {
case 0:
return true;
case 1:
case 2:
$this->_error_messages[] = "$fileName exceeds maximum file size : "
.$this->getMaxSize();
return true;
case 3:
$this->_error_messages[] = "Error while uploading $fileName.please try again.";
return false;
case 4:
$this->_error_messages[] = "No file selected.";
return false;
default:
$this->_error_messages[] = "System Error uploading $fileName.Please contact administrator.";
return false;
return false;
}
}
protected function checkSize($fileName, $size){
if($size == 0){
return false;
}else if($size > $this->_max_upload_size){
$this->_error_messages[] = "$fileName exceeds maximum size : ".
$this->_max_upload_size;
return false;
}else{
return true;
}
}
protected function checkType($fileName, $type){
if(!in_array($type, $this->_permitted_files)){
$this->_error_messages[] = 'This type of file is not allowed for uploading '
.'.please upload permitted files.';
return false;
}else{
return true;
}
}
public function checkName($input_file_name, $overwrite)
{
$input_file_name_without_spaces = str_replace(' ', '_', $input_file_name);
if($input_file_name_without_spaces != $input_file_name){
$this->_renamed_file = true;
}
if(!$overwrite){
$all_files_in_upload_directory = scandir($this->_destination_upload_folder);
if(in_array($input_file_name_without_spaces, $all_files_in_upload_directory)){
$dot_position = strrpos($input_file_name_without_spaces, '.');
if($dot_position){
$base = substr($input_file_name_without_spaces, 0, $dot_position);
$extension = substr($input_file_name_without_spaces, $dot_position);
}else{
$base = substr($input_file_name_without_spaces);
$extension = '';
}
$i = 1;
do{
$input_file_name_without_spaces = $base.'_'.$i++.$extension;
}while(in_array($input_file_name_without_spaces, $all_files_in_upload_directory));
$this->_renamed_file = true;
}
}
return $input_file_name_without_spaces;
}
protected function getMaxSize(){
return number_format(($this->_max_upload_size)/1024, 1).'kb';
}
protected function isValidMime($types)
{
$also_valid_mimes = array('application/pdf', 'text/plain', 'text/rtf');
$all_valid_mimes = array_merge($this->_permitted_files, $also_valid_mimes);
foreach($types as $type){
if(!in_array($type, $all_valid_mimes)){
throw new Exception("$type is not a valid permitted mime type!");
}
}
}
public function addPermittedType($input_type_name)
{
$input_type_name_array = (array)$input_type_name;
$this->isValidMime($input_type_name_array);
$this->_permitted_files = array_merge($this->_permitted_files, $input_type_name_array);
}
protected function processFile($fileName, $error, $size, $type, $tmp_name, $overwrite)
{
$check_upload_error = $this->checkError($fileName, $error);
if($check_upload_error){
$check_uploaded_file_type = $this->checkType($fileName, $type);
$check_uploaded_file_size = $this->checkSize($fileName, $size);
if($check_uploaded_file_type && $check_uploaded_file_size){
$new_uploaded_file_name = $this->checkName($fileName, $overwrite);
$upload_result = move_uploaded_file($tmp_name, $this->_destination_upload_folder.$new_uploaded_file_name);
if($upload_result){
$messages = $new_uploaded_file_name.' uploaded successfully! <br >';
if($this->_renamed_file){
$messages .= ' and renamed successfully!';
}
$this->_error_messages[] = $messages;
} else {
$this->_error_messages[] = 'Could`nt upload '.$fileName;
}
}
}
}
public function move($overwrite = FALSE){
$file = current($this->_uploaded);
if(is_array($file['name'])){
foreach($file['name'] as $index => $filename){
$this->_renamed_file = false;
$this->processFile($filename, $file['error'][$index],
$file['size'][$index], $file['type'][$index], $file['tmp_name'][$index], $overwrite);
}
}else{
$this->processFile($file['filename'], $file['error'], $file['size'], $file['type']
, $file['tmp_name'], $overwrite);
}
}
public function getErrorMessages(){
return $this->_error_messages;
}
public function setMaxSize($new_upload_size)
{
if(!is_numeric($new_upload_size) || $new_upload_size <= 0){
throw new Exception("new maximum upload size must a number!");
}
$this->_max_upload_size = (int)$new_upload_size;
}
}
$max_upload_size = 1024 * 1024;
if(isset($_POST['upload_button'])){
$destination_upload_folder = 'destination of upload folder here....';
require_once 'Upload class filename...';
try{
$upload = new Upload($destination_upload_folder);
$upload->setMaxSize($max_upload_size);
$upload->addPermittedType('application/pdf');
$upload->move(true);
$result = $upload->getErrorMessages();
}catch(Exception $e){
echo $e->getMessage();
}
}

Categories