Rename file after uploading

wlwan 23 Jul, 2015
Dears,
I have a form created with 5 files upload fields. Would like to set the file name as below:
"Username_"YYYYMMDDHHMMSS_1"
"Username_"YYYYMMDDHHMMSS_2"
"Username_"YYYYMMDDHHMMSS_3"
"Username_"YYYYMMDDHHMMSS_4"
"Username_"YYYYMMDDHHMMSS_5"

I can make the first part highlighted in blue, but the last part I have no idea how to make it....

The code I use as below:
<?php 
$user =& JFactory::getUser();
return $user->get('username')."_".date("YmdHis")."_".$file_name; ?>


Actually I have set those fields id and fields name as file1, file2, file3.....
not sure if can make use of these....

Thanks for your time.

Best Regards
Wing
GreyHead 23 Jul, 2015
Hi Wing,

Not tested but this might work
<?php
foreach ( $files as $k => $v ) {
  if ( $v['name'] == $file_name ) {
   $i = $k+1;
   continue;
  }
}
$user = \JFactory::getUser();
return $user->username."_".date("YmdHis")."_".$file_name."_".$i;
?>

Bob
wlwan 24 Jul, 2015
Tried but failed... :-(

I used the file named: abc.jpg
and it will be renamed as something like: admin_20150724085710_abc.jpg_

Btw, your code should be in "file name code" under "File Upload action"@onSubmit, right?
GreyHead 26 Jul, 2015
Hi Wing,

I experimented and many uploads later this version appears to work as long as there are no special characters in the file names
<?php
foreach ( $_FILES as $k => $v ) {
  if ( $v['name'] == $file_name ) {
   $i = substr($k, 4, 1);
   continue;
  }
}
$user = \JFactory::getUser();
return $user->username."_".date("YmdHis")."_".$file_name."_".$i;
?>

Bob
wlwan 27 Jul, 2015
Answer
Thanks Bob.
Have tested your code and find if....
File name: abc.jpg
Username: admin
Final uploaded file name: admin_20150724085710_abc.jpg_1

So I have modified as below and get what I want...
<?php
foreach ( $_FILES as $k => $v ) {
  if ( $v['name'] == $file_name ) {
   $i = substr($k, 4, 1);
   continue;
  }
}
$user = \JFactory::getUser();
$parts = explode(".", $file_name);
return $user->username."_".date("YmdHis")."_".$i.".".$parts[1];
?>
This topic is locked and no more replies can be posted.