[SQL與PHP] 用php下載指定檔案並重新命名(另存新檔)



[SQL與PHP] 用php下載指定檔案並重新命名(另存新檔)

上傳的程式碼(放在表單後的JavaScript):
  1. <script language="javascript">
  2. function validate()
  3. {
  4.   // 切割檔案路徑
  5.   var Ary = document.getElementById('file').value.split('\\');

  6.   // 建立隱藏標籤
  7.   var hideTag = document.createElement("input");
  8.   hideTag.setAttribute('name', 'filename');
  9.   hideTag.setAttribute('type', 'hidden');
  10.   document.getElementById('form1').appendChild(hideTag);

  11.   // 置入檔名到隱藏標籤
  12.   hideTag.value=Ary[Ary.length-1];

  13.   return true;
  14. }
  15. document.getElementById('form1').onsubmit = function() { return validate(); };
  16. </script>
複製代碼
上傳的程式碼(接收上傳檔案的PHP):
  1. <?php
  2. function ch_filename($name)
  3. {
  4.    $arr = explode('.', $name);
  5.    $arr[0] = (rand()%100).substr(md5($arr[0]), 0, 28);
  6.    return join('.', $arr);
  7. }

  8. if($_FILES['file']['size'] > 0)
  9. {
  10.    $filename = ch_filename($_POST['filename']);
  11.    move_uploaded_file($_FILES['file']['tmp_name'],'upload/'.$filename);
  12.    
  13.    // 新增資料到資料庫(filepath|filename)
  14.    $db->query("UPDATE `news` SET `file` = '".$_POST['filename']."|upload/".$filename."';");
  15. }
  16. ?>
複製代碼
下載的超連結:$filename <= 這個是要顯示給使用者看到的名稱(包含副檔名)
  1. <a href="get_file.php?path=<?=$filepath?>&filename=<?=urlencode($filename)?>"><?=$filename?></a>
複製代碼
get_file.php 程式碼:
  1. <?php
  2. if(empty($_GET['path']) || empty($_GET['filename']))
  3. {
  4.    echo '非正常路途徑進入本頁或參數錯誤';
  5.    exit();
  6. }

  7. if(file_exists($_GET['path']))
  8. {
  9.    $FILEname = urlencode($_GET['filename']);
  10.    
  11.    if(ini_get('zlib.output_compression'))
  12.       ini_set('zlib.output_compression', 'Off');
  13.    
  14.    header("Content-Type: application/octetstream; name=$FILEname"); //for IE & Opera
  15.    
  16.    header("Content-Type: application/octet-stream; name=$FILEname"); //for the rest
  17.    
  18.    header("Content-Disposition: attachment; filename=$FILEname;");
  19.    
  20.    header("Content-Transfer-Encoding: binary");
  21.    header("Cache-Control: cache, must-revalidate");
  22.    header("Pragma: public");
  23.    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  24.    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
  25.    
  26.    readfile($_GET['path']);
  27.    //若無法使用,請改成readfile($_GET['path']."/".$_GET['filename']);
  28. }
  29. else
  30.    echo '檔案不存在';
  31. ?>
複製代碼