2017-04-26 590 views
1

我知道move_uploaded_file()設置上傳文件的名稱並設置目的地。我有這樣的:PHP move_uploaded_file重命名文件

$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable 
$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/img/profiles/'.$_FILES['file']['name']; // Target path where file is to be stored 
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file` 

我已經試過爆炸$_FILES['file']['tmp_name'],但我沒有得到改變我的上傳文件的名字我的POST變量$newfile=$_POST["something"];

預先感謝您

+0

沒有得到你的問題正確。你想使用張貼變量作爲文件名? '$ targetPath = $ _SERVER ['DOCUMENT_ROOT']。 「/ IMG /型材/'.$_ POST [ 「東西」];'? – bansi

+0

是的,完全......謝謝,但問題是文件的擴展。現在我明白了。我做了'$ ext = explode('。',$ _FILES ['file'] ['name']);' –

回答

1

我使用

//文件名

$file_name = $_FILES["file"]["name"]; 
$file_name = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file_name); 

//獲取ecxtension

$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION); 

//改變名稱

$imagename = $file_name . time() . "." . $ext; 
+0

非常感謝! –

1

將整個使用$ targetpath變量中的文件名上傳路徑。 在你的代碼

$sourcePath = $_FILES['file']['tmp_name']; 
$newfile=$_POST["something"]; //any name sample.jpg 
$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/img/profiles/'.$newfile; 
move_uploaded_file($sourcePath,$targetPath) ; 

現在上傳的文件名是sample.jpg 我認爲你這會有所幫助。