![](/img/trans.png)
[英]php rename uploaded file before upload and overwrite if already exists
[英]PHP - upload and overwrite a file (or upload and rename it)?
我已經在這個問題上進行了廣泛的搜索,但還沒有真正找到解決方案。
有一個客戶想要在他們的網站上播放音樂(是的,是的,我知道..)。 Flash 播放器抓取名為 song.mp3 的單個文件並播放它。
好吧,我正在嘗試獲得功能,以便能夠讓客戶上傳他們自己的新歌曲,如果他們想要更改它。
所以基本上,腳本需要允許他們上傳文件,然后用新文件覆蓋舊文件。 基本上,確保 song.mp3 的文件名保持不變。
我想我需要使用 PHP 來 1) 上傳文件 2) 刪除原來的 Song.mp3 3) 將新文件重命名為 Song.mp3
這看起來對嗎? 或者有沒有更簡單的方法來做到這一點? 提前致謝!
編輯:我impimented UPLOADIFY 並且能夠使用
'onAllComplete' : function(event,data) {
alert(data.filesUploaded + ' files uploaded successfully!');
}
我只是不確定如何將其指向 PHP 文件....
'onAllComplete' : function() {
'aphpfile.php'
}
??? 哈哈
標准表單就足以上傳,只需記住在表單中包含 mime。 那么您可以使用 $_FILES[''] 來引用該文件。
然后您可以檢查提供的文件名並使用 file_exists() 檢查文件系統中是否存在文件名或者如果您不需要保留舊文件,您可以使用執行文件移動並覆蓋舊文件一個來自臨時目錄的 new
<?PHP
// this assumes that the upload form calls the form file field "myupload"
$name = $_FILES['myupload']['name'];
$type = $_FILES['myupload']['type'];
$size = $_FILES['myupload']['size'];
$tmp = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name.".".$type;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
// echo "The file $filename exists";
// This will overwrite even if the file exists
move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way
?>
試試這段代碼上傳和替換文件
if(file_exists($newfilename)){
unlink($newfilename);
}
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newfilename);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.