I have this code, to upload multiple files.
I would like to add a custom name for each file, beacuse i will store them in sql like this:
filename-1-2017-05-02-12:30:00 (1 is the actual array index, and after a date time)
if(isset($_POST['submitButton']))
{
if(isset($_FILES['gallery']))
{
if($_FILES["gallery"]["size"] > 0 )
{
foreach($_FILES['gallery']["name"] AS $key=>$file)
{
if($_FILES['gallery']['size'][$key] != 0 )
{
$target_path = "../documents/";
$target_path = $target_path . $_FILES['gallery']['name'][$key];
printr($_FILES['gallery']);
die();
if(move_uploaded_file($_FILES['gallery']['tmp_name'][$key], $target_path))
{
//$file_name = basename($_FILES['dok_file']['name']);
header("Location: ".$host."/".$admin_folder."/feltoltott-fajlok.php?new=1");
}
else
{
$error[] = "A fájl feltöltése nem sikerült, próbálja újra.";
}
}
}
}
}
}
http://php.net/manual/en/function.date.php
$target_path = "../documents/" . $_FILES['gallery']['name'][$key] . "-$key-" . date( "Y-m-d-H:i:s" );
move_uploaded_file( $_FILES['gallery']['tmp_name'][$key], $target_path );
Related
add.php(When user click add photo)
<div class="col-lg-12">
<div class="form-group" id="image">
<label>Auction Image</label>
<div action="uploadImages.php" class="dropzone" id="uploadImageForm"></div>
<span class="help-block" id="image-error"></span>
</div>
</div>
<script>
$(function () {
Dropzone.options.uploadImageForm = false;
Dropzone.options.uploadImageForm = {
paramName: "file",
maxFilesize: 1,
acceptedFiles: 'image/*',
maxFiles: 5,
dictDefaultMessage: '<img src="images/icon_images.svg" width="100"/><br/><br/>Drop auction image here',
addRemoveLinks: true,
removedfile: function(file) {
var name = file.name;
$.ajax({
type: 'POST',
url: 'delete.php',
data: "id="+name,
dataType: 'html'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
};
</script>
UploadImages.php
<?php
session_start();
require 'config/database.php';
if (!isset($_SESSION['user'])) {
exit;
}
else if (!empty($_FILES)) {
$auctionImage = array();
$size = getimagesize($_FILES['file']['tmp_name']);
if (!$size) {
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode(['error']);
exit;
}
else {
$n = 0;
$tempFile = $_FILES['file']['tmp_name'];
$imageName = uniqid() . '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$targetPath = dirname( __FILE__ ) . '/images/uploads/';
$targetFile = $targetPath . $imageName;
$filename = $_FILES["file"]["name"];
move_uploaded_file($tempFile,$targetFile);
// isset id = insert gallery image into database
if (isset($_GET['id'])) {
$stmt = $db->prepare("INSERT INTO image (user_id, related_id, related_type, url) VALUES (:uid, :id, 'gallery', :url)");
$stmt->bindParam(':uid', $_SESSION['user']['id']);
$stmt->bindParam(':id', $_GET['id']);
$stmt->bindParam(':url', $imageName);
$stmt->execute();
}
else {
$auctionImage[] = $filename;
}
}
if (!empty($auctionImage)) {
// record uploaded image name, will store into session
// store uploaded image into session
//$_SESSION["auctionImages"] = array();
$_SESSION["auctionImages"][] = $auctionImage;
}
}
delete.php
<?php
$targetPath = dirname( __FILE__ ) . '/images/uploads/';
unlink($targetPath.$_POST['id']);
session_start();
$a = $_POST['id'];
$key=array_search($a,$_SESSION['auctionImages']);
if($key!==false){
unset($_SESSION['auctionImages'][$key]);
$_SESSION["auctionImages"] = array_values($_SESSION["auctionImages"]);
echo '<pre>'; print_r($_SESSION['auctionImages']);
}
To use session variables, please add session_start() at the begin of your files, otherwise they aren't used. Secondly you are adding an array into a next array.
so you have to use
$_SESSION["auctionImages"] = $auctionImage;
or
$key=array_search($a[0],$_SESSION['auctionImages']);
Further debugging can be done by print_r($_SESSION); so you can track the contents of this array
The Problem -- What you should do:
You basically have to populate the SESSION variable like this:
$_SESSION["auctionImages"] = array(
"IMG_2923.JPG", "IMG_2924.JPG"
);
You're meant to address each element therefore, like this:
$_SESSION["auctionImages"][$n];
$n is the numbered index value for a particular element in the array. Therefore, if $n is 0, the array would return "IMG_29.29.JPG" and if the $n is 1, the array would return "IMG_2924.JPG".
However, you are populating the array like this:
$_SESSION["auctionImages"][] = array(
"IMG_2923.JPG", "IMG_2924.JPG"
);
If you dump this array, it will give you:
array(
array(
"IMG_2923.JPG", "IMG_2924.JPG"
)
);
Which is not the behaviour you require.
Solution
$filename = $_FILES["file"]["name"];
if(!is_array($_SESSION["auctionImages"])) {
$_SESSION["auctionImages"] = [];
}
$_SESSION["auctionImages"][] = $filename;
This is more shorter, cleaner and neater.
Also, you can use the alternative array syntax which is [ and ]. So, you can declare arrays using $var = []; which is shorter than $var = array();.
Firstly, the variable $a is the text to be searched in the array.
$key = array_search($a, $_SESSION["auctionImages"]);
if ($key !== false) {
unset($_SESSION["auctionImages"][$key]);
}
This is the second part of the code. This is all you need to have.
Also, make sure you have started the session by invoking session_start() in the top of the file if you haven't done yet.
A few comments
Consider taking a look at the Unofficial PHP standards here. It would be better if you name your variables in $camelCase. Therefore, it would be better to rename $filename to $fileName.
Also good job on using strict comparison which is !==.
Also, use more meaningful variable names. $a does not make sense. Something like $searchString would be really meaningful and the code will self-document your code.
Links
is_array - Returns TRUE if the passed identifier is an array, otherwise returns FALSE.
Let's now solve the problem with the full code you have given me. Let's start with delete.php:
<?php
session_start();
$targetPath = dirname( __FILE__ ) . '/images/uploads/';
if(!isset($_POST['id'])) {
echo "ID has not been defined!";
exit;
}
$id = $_POST['id'];
unlink($targetPath . $id);
$key = array_search($id, $_SESSION['auctionImages']);
if ($key !== false) {
unset($_SESSION['auctionImages'][$key]);
echo '<pre>';
print_r($_SESSION['auctionImages']);
}
Now, let's fix your UploadImages.php file:
<?php
session_start();
require 'config/database.php';
if (!isset($_SESSION['user'])) {
exit;
}
if (!empty($_FILES)) {
if(!isset($_SESSION["auctionImages"]) && !is_array($_SESSION["auctionImages"])) {
$_SESSION["auctionImages"] = [];
}
$size = getimagesize($_FILES['file']['tmp_name']);
if (!$size) {
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode(['error']);
exit;
}
else {
$tempFile = $_FILES['file']['tmp_name'];
$imageName = uniqid() . '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$targetPath = dirname( __FILE__ ) . '/images/uploads/';
$targetFile = $targetPath . $imageName;
$fileName = $_FILES["file"]["name"];
move_uploaded_file($tempFile, $targetFile);
// isset id = insert gallery image into database
if (isset($_GET['id'])) {
$stmt = $db->prepare("INSERT INTO image (user_id, related_id, related_type, url) VALUES (:uid, :id, 'gallery', :url)");
$stmt->bindParam(':uid', $_SESSION['user']['id']);
$stmt->bindParam(':id', $_GET['id']);
$stmt->bindParam(':url', $imageName);
$stmt->execute();
}
else {
$_SESSION["auctionImages"][] = $fileName;
}
}
}
You have a problem here
$_SESSION["auctionImages"][]= $auctionImage;
Variable $auctionImage itself an array so need not to assign as an array again in SESSION variable. Make it as
$_SESSION["auctionImages"]= $auctionImage;
It works fine for me.
below is the code I worked.
<?php
//$filename = $_FILES["file"]["name"];
$auctionImage = array();
$auctionImage = array('IMG_2923.JPG', 'IMG_2924.JPG', 'IMG_2925.JPG'); // assigning sample variables // will be IMG_2923.JPG, IMG_2924.JPG and etc
$_SESSION["auctionImages"]= $auctionImage; // Removed '[]' from your coding
$a = 'IMG_2923.JPG'; // Assigning for testing purpose
$key=array_search($a,$_SESSION['auctionImages']);
if($key!==false)
unset($_SESSION['auctionImages'][$key]);
$_SESSION["auctionImages"] = array_values($_SESSION["auctionImages"]);
echo '<pre>'; print_r($_SESSION['auctionImages']); // Printing final session value. It prints without the key image name
?>
Earlier I have a form that ask user to upload a picture and I have this function:
function fileUploaded() {
$fileName = $_FILES ['picture'] ['name'];
$pathOfFile = "/images/";
$fileTmpLoc = $_FILES ['picture'] ["tmp_name"];
$fileResult = move_uploaded_file ( $fileTmpLoc, $pathOfFile );
if (isset ( $fileName )) {
return true;
}
}
Basically it moves the uploaded picture to images file. Then I am calling this function in an if statement:
if (fileUploaded () == true) {
if ($fileResult) {
/*checking the size of file*/
}
}
else {
$fileName = "default.jpg";
}
After when I try to upload and submit it gives the error in the below:
Fatal error: Call to undefined function fileUploaded()
What should be the problem?
Thanks.
You don't return a default value in your function. Maybe it's the problem :
function fileUploaded() {
$fileName = $_FILES ['picture'] ['name'];
$pathOfFile = "/images/";
$fileTmpLoc = $_FILES ['picture'] ["tmp_name"];
$fileResult = move_uploaded_file ( $fileTmpLoc, $pathOfFile );
if (isset ( $fileName )) {
return true;
}
return false;
}
//functions.php
function fileUpload($path) {
if(!isset($_FILES['picture'])) return false;
$fileName = $_FILES['picture']['name'];
$fileTmpLoc = $_FILES['picture']['tmp_name'];
if(move_uploaded_file ($fileTmpLoc, $path)) return $fileName;
return false;
}
//main.php
include('functions.php');
$fileName = fileUpload('/images/');
if($fileName === false) {
$fileName = 'default.jpg';
}
//do the rest here
Something similar to the above code. Since your function is in a different file, you need to include it (or require it)
i am using the code bellow to upload images to my wp directory.
I tried to modified the code so i can download images directly from the url but i didnt have any luck.
My code is bellow:
<?php
class imgUploader
{
var $exts = array( ".png", ".gif", ".png", ".jpg", ".jpeg" ); //all the extensions that will be allowed to be uploaded
var $maxSize = 9999999; //if you set to "0" (no quotes), there will be no limit
var $uploadTarget = "../wp-content/uploads/"; //make sure you have the '/' at the end
var $fileName = ""; //this will be automatically set. you do not need to worry about this
var $tmpName = ""; //this will be automatically set. you do not need to worry about this
public function startUpload()
{
$this->fileName = $_FILES['uploaded']['name'];
$this->tmpName = $_FILES['uploaded']['tmp_name'];
if( !$this->isWritable() )
{
die( "Sorry, you must CHMOD your upload target to 777!" );
}
if( !$this->checkExt() )
{
die( "Sorry, you can not upload this filetype!" );
}
if( !$this->checkSize() )
{
die( "Sorry, the file you have attempted to upload is too large!" );
}
if( $this->fileExists() )
{
die( "Sorry, this file already exists on our servers!" );
}
if( $this->uploadIt() )
{
echo "Your file has been uploaded!<br><br>Click here to view your file!";
}
else
{
echo "Sorry, your file could not be uploaded for some unknown reason!";
}
}
public function uploadIt()
{
return ( move_uploaded_file( $this->tmpName, $this->uploadTarget . time() . $this->fileName ) ? true : false );
}
public function checkSize()
{
return ( ( filesize( $this->tmpName ) > $this->maxSize ) ? false : true );
}
public function getExt()
{
return strtolower( substr( $this->fileName, strpos( $this->fileName, "." ), strlen( $this->fileName ) - 1 ) );
}
public function checkExt()
{
return ( in_array( $this->getExt(), $this->exts ) ? true : false );
}
public function isWritable()
{
return ( is_writable( $this->uploadTarget ) );
}
public function fileExists()
{
return ( file_exists( $this->uploadTarget . time() . $this->fileName ) );
}
}
$img = new imgUploader();
if( $_POST['upload_file'] )
{
$img->startUpload();
}
else
{
echo "<form method=\"post\" enctype=\"multipart/form-data\">
<p>
<label for=\"file\">Select a file to upload:</label> <input type=\"file\" name=\"uploaded\" id=\"file\"><br>
<input type=\"submit\" name=\"upload_file\" value=\"Upload!\">
<p>
</form>";
}
?>
I tried to remove the hole form and give to $filename and $temp name the image url but it doesnt work..
any idea?
I've been struggling with this for a while now and hoping someone can point me in the right direction. I have a script that works for uploading a single image. I'm now trying to amed it so that I can update more than 1 file at once. 2 in the example below. I understand that name needs to be an array and I loop through them however I only seem to be encountering errors. I've read and tried various different things.
I either was able to upload one file but not the second, upload no files or a blank white screen.
Below is what I'm currently working with after having various edits.
<?php
$upload_dir= 'training/trainingDocuments';
$numUploads = 2;
$msg = 'Please select files for uploading';
$errors = array();
if(isset($_FILES['myTrainingFile']['tmp_name']))
{
for($i=0; $i < count($_FILES['myTrainingFile']['tmp_name']);$i++)
{
$fileName = $_FILES['myTrainingFile']['name'][$i];
$tempName = $_FILES['myTrainingFile']['tmp_name'][$i];
$blacklist = array('exe','php','jsp','js','bat','asp','aspx','com','dmg');
$a = explode('.', $fileName);
$fileExt = strtolower(end($a)); unset($a);
$fileSize = $_FILES['myTrainingFile']['size'];
if(in_array($fileExt, $blacklist) === true){
$errors[] = "File type not allowed";
}
//$newPath = $general->fileNewPath($path, $fileName);
$newPath = "training/trainingDocuments/" . $_FILES['myTrainingFile']['name'][$i];
$moveFileResult = move_uploaded_file($tempName, $newPath);
if($moveFileResult != true){
$errors[] = 'Upload Failed - MOVE';
}
$comments = htmlentities(trim($_POST['comments']));
$category = htmlentities(trim($_POST['category']));
//insert into db
$training->uploadDocument($fileName, $category, $comments);
if(!is_uploaded_file($_FILES['myTrainingFile']['name'][$i]))
{
$errors[] = 'Uploading '.$_FILES['myTrainingFile']['name'][$i] . 'failed -.-';
}
}
}
?>
Thanks for any help!
Try this code, i added a function named convert_files, so you can handle your uploads in a better way
Code:
<?php
$upload_dir = "training/trainingDocuments";
$numUploads = 2;
$msg = "Please select file(s) for uploading";
$errors = array();
// how many files you want to upload
$maxFiles = 3;
if ( $files = convert_files( $_FILES["myTrainingFile"] ) ) {
foreach( $files as $i => $file ) {
$fileName = $file["name"];
$tempName = $file["tmp_name"];
$fileSize = $file["size"];
// get file extension, and do strtolower
$fileExt = strtolower( pathinfo( $fileName, PATHINFO_EXTENSION ) );
// invalid file types
$blacklist = array( 'exe','php','jsp','js','bat','asp','aspx','com','dmg' );
// new path to upload current file
$newPath = "training/trainingDocuments/".$fileName;
// Check whether its a valid file or invalid file
if ( in_array( $fileExt, $blacklist ) ) {
// invalid file type, add error
$errors[$i] = "File type not allowed";
}
if ( !is_uploaded_file( $tempName ) ) {
// its'' not an uploaded file, add error
$errors[$i] = "Uploading ".$fileName." failed -.-";
}
if ( file_exists( $newPath ) ) {
// file already exists in your directory, add error
$errors[$i] = "File ".$fileName." already exists";
// if you dont want to add error, (adding an error will not upload file)
// just comment above line, and uncomment below line
/*
// get the filename without extension
$name = pathinfo( $fileName, PATHINFO_FILENAME );
//create new file name
$fileName = $name."_".uniqid().".".$fileExt;
//update upload path
$newPath = "training/trainingDocuments/".$fileName;
*/
}
// make sure $errors[$i] contains any errors
if ( isset( $errors[$i] ) ) {
// errors occured, so continue to next file
continue;
}
if ( !move_uploaded_file( $tempName, $newPath ) ) {
$errors[$i] = "Upload Failed - MOVE"; // failed to move file
}
$comments = htmlentities( trim( $_POST['comments'] ) );
$category = htmlentities( trim( $_POST['category'] ) );
// Upload document
$training->uploadDocument( $fileName, $category, $comments );
// check maximum allowed files limit exceeded
if ( ( $i + 1 ) == $maxFiles ) {
// limit exceeded, break the execution
break;
}
}
}
?>
Function:
<?php
function convert_files( $files ) {
if ( is_array( $files ) && !empty( $files["name"] ) ) {
if ( is_array( $files["name"] ) ) {
$merged = array();
foreach( $files["name"] as $i => $name ) {
$merged[] = array(
"name" => $name,
"type" => $files["type"][$i],
"size" => $files["size"][$i],
"error" => $files["error"][$i],
"tmp_name" => $files["tmp_name"][$i]
);
}
return $merged;
}
return array( $files );
}
return false;
}
?>
I currently have this script where users (using a form where they can upload up to seven images) can upload multiple images to a folder and the image name to my database, without any success. Please help.
if (isset($_POST['submit'])) { $ref_49 = $_POST['ref_49'];
$name = $_POST['name'];
$contact = $_POST['contact'];
$email = $_POST['email'];
$rent_sell = $_POST['rent_sell'];
$heading = $_POST['heading'];
$price = $_POST['price'];
$limitedtextarea = $_POST['limitedtextarea'];
$type = $_POST['type'];
$where = $_POST['where'];
$address = $_POST['address'];
$bedroom = $_POST['bedroom'];
$bathroom = $_POST['bathroom'];
$garages = $_POST['garages'];
$carports = $_POST['carports'];
$granny_flat = $_POST['granny_flat'];
$ref_99 = $_POST['ref_99'];
$fulldesc = $_POST['full_desc'];
if ($ref_99=="") {
$full_ad = "yes";
} else {
$full_ad = "no";
}
$todays_date = date("Y-m-d");
mkdir("gallery/" . $_POST["name"], 0777);
for ($i = 0; $i < 7; $i++)
{
$file_name = $_FILES['uploadFile' . $i]['name'];
// strip file_name of slashes
$file_name = stripslashes($file_name);
$file_name = str_replace("'", "", $file_name);
// $copy = copy($_FILES['uploadFile'. $i]['tmp_name'], "gallery/" . $_POST["name"] . "/" . $file_name);
if ((($_FILES['uploadFile' . $i]["type"] == "image/gif")
|| ($_FILES['uploadFile' . $i]["type"] == "image/jpeg")
|| ($_FILES['uploadFile' . $i]["type"] == "image/pjpeg"))
&& ($_FILES['uploadFile' . $i]["size"] < 200000000))
{
if ($_FILES['uploadFile' . $i]["error"] > 0)
{
$message = "Return Code: " . $_FILES['uploadFile' . $i]["error"] . "<br />";
}
else
{
$query = "INSERT INTO property (
name, contact, email, type_of_listing, rent_sell, address, prop_desc, area, price, main_image, image_1, image_2, image_3, image_4, image_5, image_6, heading, bathroom, bedroom, garages, carports, granny_flat, full_description, full_ad, 49_ref, 99_ref, listed
) VALUES (
'{$name}', '{$contact}', '{$email}', '{$type}', '{$rent_sell}', '{$address}', '{$limitedtextarea}', '{$where}', '{$price}', '{$photo_1}', '{$photo_2}', '{$photo_3}', '{$photo_4}', '{$photo_5}', '{$photo_6}', '{$photo_7}', '{$heading}', '{$bathroom}', '{$bedroom}', '{$garages}', '{$carports}', '{$granny_flat}', '{$fulldesc}', '{$full_ad}', 'ref_49_{$ref_49}', 'ref_99_{$ref_99}', ''
)";
$result = mysql_query($query, $connection);
if (file_exists("gallery/" . $_POST["name"] . "/" . $_FILES['uploadFile' . $i]["name"]))
{
$message = "<h3>" . $_FILES['uploadFile' . $i]["name"] . " already exists.</h3>";
}
else
{
move_uploaded_file($_FILES['uploadFile' . $i]["tmp_name"], "gallery/" . $_POST["name"] . "/" . $_FILES['uploadFile' . $i]["name"]);
$message = "File: " . $_FILES['uploadFile' . $i]["name"] . " uploaded.";
}
}
}
else
{
$message = "<h3>Invalid file or no file selected.</h3><br />• Only JPEG OR GIF allowed.<br />• Size limited may not exceed 200KB.<br />Return";
}
}
}
}
There could be a lot of things going wrong here. Have you tried to break this up into pieces? Are you sure the DB is connecting? Are you sure php has access to write to the directories it's attempting to write to? Are you sure those directories exist...etc. etc.
Comment out the vast majority of the code, and start testing all the components piece by piece, or wrap stuff in try/catch and see what errors are produced.
[edit]
If the problem only occurs when you upload < 7 files then the problem is in that you've hard coded a 7 into your loop!
Loop through how many files are actually being uploaded, not a fixed number.
Assuming they're all being named sequentially (and starting at 0) you can test for the existence of your hashed FILE value in the loop and just keep ingesting until it comes up null (probably good to add a limiter to make sure it can't go on for ever)
something like this...
[edit 2] modified the condition to include a test for file size
for($i=0; $_FILES['uploadFile' . $i] && $_FILES['uploadFile' . $i]['size'] > 0 && $i<100 ; $i++){
try{
//do your upload stuff here
}catch(e){}
}
[EDIT]
To modify your page to include a dynamic number of fields do this:
check out this fiddle: http://jsfiddle.net/RjcHY/2/
Click the plus and minus buttons on the right side to see how it works. I made it so that it's naming the file buttons as per your php's expectations.
While dealing with common tasks like file uploading, write some library for handling those tasks and call necessary function wherever needed . If you create an uploader class file , you can simply invoke one of the methods you created to handle file uploads .
Here i will give you a Uploader class
<?php
//Save file as Uploader.php
//File Uploading Class
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:iConfused')).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);
}
}
?>
Using Uploader.php
<?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
}
?>
For handling multiple uploads , ex 3 images uploading
repeat the block as follows
<?php
for($i=1;$i<=3;$i++){
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list//
$uploader->setMaxSize(.5); //set max file size to be allowed in MB//
$uploader->setSequence($i);
if($uploader->uploadFile('txtFile'.$i)){ //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
}
}
?>
in above example , file browse components are named as txtFile1,txtFile2,txtFile3
Hope you will understand my explanation .