Download files from server with timestamp

I have the following code which timestamps all files uploaded to the server. As a result each file is unique. I’m trying to download each file but can’t use the _FILES[file][‘name’] global since that won’t work. How should I go about downloading my files?

Uploading code:

[php]
$upload_dir = ‘repository/’;

if (isset($_POST[‘addfile’])){

$tempFile = $_FILES['file']['tmp_name'];
$FileName = $_FILES['file']['name'];
$file_type = $_FILES['file']['type'];
// using DIRECTORY_SEPARATOR constant is a good practice, it makes your code portable.
$targetPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . $upload_dir . DIRECTORY_SEPARATOR;
// Adding timestamp with image's name so that files with same name can be uploaded easily.
$mainFile = $targetPath.date("Y-m-d H-i-s").'-'. $_FILES['file']['name'];
//get variables for database			
$projectname=$_POST['projectname'];
$version= $_POST['version'];					
$comments=$_POST['comments'];

if(move_uploaded_file($tempFile,$mainFile)){
	include 'db.php';
	$add = mysql_query("INSERT INTO `myversions`(filename, filetype, projectname, version, comments, created) 
	VALUES ('$FileName', '$file_type','$projectname','$version','$comments', NOW())"); 		

echo "Your file “. basename( $_FILES[‘file’][‘name’]). " has been successfully uploaded and recorded in the database!”;
}
else {
echo “Your file failed to upload.”;
}
}
[/php]

View code:
[php]
include(“db.php”);

	//Show all files
	$result = mysql_query("SELECT * FROM myversions ORDER by projectname ASC, created DESC");

	echo "<div class='table-responsive'>";
			echo "<table class='table table-striped table-bordered'>";
			echo "<thead>";
			echo "<tr>";
			echo "<th>File Name</th><th>Project Name</th><th>Version</th><th>Comments</th><th>Created</th>";
			echo "</tr></thead>";
			echo "<tbody>";  
		
	while($row = mysql_fetch_array($result)){
		$id = $row['id'];	
			echo "
			<tr>
			<td>$row[filename]</td>
			<td>$row[projectname]</td>
			<td>$row[version]</td>
			<td>$row[comments]</td>
			<td>$row[created]</td>
			<td><a href='#'>Download File</a></td>
			</tr>";  		
	}

	echo "</tbody>"; 
	echo "</table>";
	echo "</div>"; 

	//close connection
	mysql_close($conn)

[/php]

What do you have in the table, as in table structure? If the file is actually stored in the database, you would need to select the primary key so you could view/ download it. If it is being held in a directory, ie uploads, you would need to store the path to the file and select that.

The files are located in a directory. The problem is I could list the file path but the names are all unique so how would I get the system to find the file name so that the file could be downloaded?

For example, the files after upload look like the following:
06-20-15 07:08:00PM-somefile.php

It’s not complicated. Even easier if all the files are in the same place.

[php]somefile1
somefile2
somefile3
[/php]

The database should be able to give filenames. The rest is prepending where it was loaded to.

So would it look something like the following:
[php]<?php echo "$row[filename]"; ?>[/php]

I don’t know how you plan on printing them, but more like this,

[php]<?php echo "{$row['filename']}"; ?>[/php]

Your way would throw errors and unexpected results. Also, using a loop would be more effective.

Yes, I’ll probably put that in the while loop that fetches all the values like in the above view code. One last thing, how would I reference the ID of each record in that href so it could be something like:

directory location -> id -> filename from database.

Thanks.

I would hope you could figure that out.

One last thing then. How could I switch from date timestamps to a counter timestamp such that each file would get renamed as follows: Version 1-test.php if the file already existed and the date/time modified was different than the original file. Thanks.

The way you have it setup, that would never happen. If you want to go that route, drop the datetime stamp on the file altogether. You make the file name unique. And on duplicate, modify the filename.

This is what I have so far. The integer Value in the “Major” version works flawlessly and adds Ver_1 as expected. However, when it comes to the double I can’t seem to get it to increment correctly. Instead the page just times out whenever I select a minor revision from the selectbox. If something was mispelled it would have errored out right away so I’m thinking it has something to do with how the variable is assigned. Any thoughts?

[php]if ( isset( $_POST[‘addfile’] ) ) {

// variables
define('UPLOAD_DIR', 'repository/'); 
$fileName = $_FILES['fileToUpload'];

if($_POST['rev_type'] == 'Minor') {
    
	function update_file_name_minor($file) 
    {
      $pos = strrpos($file,'.');
      $ext = substr($file,$pos); 
      $dir = strrpos($file,'/');
      $dr  = substr($file,0,($dir+1)); 

      $arr = explode('/',$file);
      $fName = substr($arr[(count($arr) - 1)], 0, -strlen($ext));

      $exist = FALSE;
      $i = 0.01;

      while(!$exist)
      {
        $file = $dr.$fName.'_'.'Ver '.$i.$ext;
  
        if(!file_exists($file))
          $exist = TRUE;
  
        $i + 0.01;
      }

      return $file;
    }
	
    // check for which action should be taken if file already exist
    if(file_exists(UPLOAD_DIR . $fileName['name'])) 
    {
      $updatedFileName = update_file_name_minor(UPLOAD_DIR.$fileName['name']);
      move_uploaded_file($fileName['tmp_name'], $updatedFileName);

      echo "You have successfully uploaded and renamed the file as a minor revision.";
    }
    else
    {
      move_uploaded_file($fileName['tmp_name'], UPLOAD_DIR.$fileName['name']);

     echo "You have successfully uploaded the file.";
    }
					
}

elseif($_POST['rev_type'] == 'Major') {
	
	function update_file_name_major($file) 
    {
      $pos = strrpos($file,'.');
      $ext = substr($file,$pos); 
      $dir = strrpos($file,'/');
      $dr  = substr($file,0,($dir+1)); 

      $arr = explode('/',$file);
      $fName = substr($arr[(count($arr) - 1)], 0, -strlen($ext));

      $exist = FALSE;
      $i = 2;

      while(!$exist)
      {
        $file = $dr.$fName.'_'.'Ver '.$i.$ext;
  
        if(!file_exists($file))
          $exist = TRUE;
  
        $i++;
      }

      return $file;
    }
	
    // check for which action should be taken if file already exist
    if(file_exists(UPLOAD_DIR . $fileName['name'])) 
    {
      $updatedFileName = update_file_name_major(UPLOAD_DIR.$fileName['name']);
      move_uploaded_file($fileName['tmp_name'], $updatedFileName);

      echo "You have successfully uploaded and renamed the file as a major revision.";
    }
    else
    {
      move_uploaded_file($fileName['tmp_name'], UPLOAD_DIR.$fileName['name']);

     echo "You have successfully uploaded the file.";
    }			
}			

} //main if[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service