2013-12-07 75 views
0

我有這段代碼來上傳jpg文件。我需要重命名某人上傳到newtexture.jpg的文件。如何在php中更改上傳文件的名稱?

<?php 
$demo_mode = false; 
$upload_dir = 'uploads/'; 
$allowed_ext = array('jpg','jpeg'); 

if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){ 
    exit_status('Error! Wrong HTTP method!'); 
} 

if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0){ 
    $pic = $_FILES['pic']; 
    if(!in_array(get_extension($pic['name']),$allowed_ext)){ 
     exit_status('Only '.implode(',',$allowed_ext).' files are allowed!'); 
    } 
    if($demo_mode){ 
     $line = implode('  ', array(date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name'])); 
     file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND); 
     exit_status('Uploads are ignored in demo mode.'); 
    } 
    if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){ 
     exit_status('File was uploaded successfuly!'); 
    } 
} 
exit_status('Something went wrong with your upload!'); 

function exit_status($str){ 
    echo json_encode(array('status'=>$str)); 
    exit; 
} 

function get_extension($file_name){ 
    $ext = explode('.', $file_name); 
    $ext = array_pop($ext); 
    return strtolower($ext); 
} 
?> 

PS。它說它大部分是編碼的,以便添加更多細節?還有什麼...我是學生,我需要它爲我的凱普斯通項目,這是一個緊急情況...

回答

4

move_uploaded_file()的第二個參數是新的文件名,所以你需要做的就是改變它到什麼你要。

if(move_uploaded_file($pic['tmp_name'], $upload_dir.'newtexture.jpg')){ 
+1

謝謝!我希望我有超過15的聲望:) –

+0

@FragkiskosMysirlakis其實,你現在做:) – Popnoodles

+0

是的,哈哈我現在有... –

1

通過你的文件名作爲第二個參數中move_uploaded_file()

$fileName = 'newtexture.jpg'; 

if(move_uploaded_file($pic['tmp_name'], $upload_dir.$fileName)){ 
1

move_uploaded_file需要參數:

  1. 臨時文件名移動。
  2. 新的永久文件路徑。
bool move_uploaded_file (string $filename , string $destination) 

所以,你必須指定第二個參數(路徑+新的文件名)。 例如

move_uploaded_file($pic['tmp_name'], $upload_dir.'newtexture.jpg') 
相關問題