Wednesday, October 23, 2013

php, upload file same name



I upload mp3 files using PHP, I want to check if the file exists, then change the file name.
using
$filebase = basename($filename, ".mp3");
to get the filename without mp3 extension, for example test.mp3, we get test.
If test.mp3 exists, the upload file name will be changed to test_1.mp3, test_2.mp3 ... in sequence.
The final PHP code is as follows
<?php
$filetmpname = $_FILES['newfile']['tmp_name'];    
$filename=$_FILES['newfile']['name'] ;
 $basedir="C:\\LMS_CESEI\\file_repository\\";
$filebase = basename($filename, ".mp3");
$i=0;
while(file_exists($basedir.$filename)) {
$i = $i +1;
$filename = $filebase.'_'.$i.'.mp3';
}
$ok = move_uploaded_file($filetmpname, $basedir.$filename);

?>

To see the list of files uploaded in the remote directory
<?php
$basedir=
"C:\\LMS_CESEI\\file_repository\\";
 if ($handle = opendir($basedir)) {
      while (false !== ($file = readdir($handle))) {
          if ($file == '.' || $file == '..') {
            continue;
          }
          echo $file."<br />";
        }
}
?>

No comments:

Post a Comment