2015-10-21 56 views
1

我知道,也有这个问题,很多解决方案,但遗憾的是我没能解决它,这是我上传的代码:PHP上传isset和重命名文件,如果它的存在

public static function upload(&$file, $destinationDir = "", $destinationName = "", $secure = true) 
    { 
$ret = false; 

if (isset($file['tmp_name']) && isset($file['name'])) 
{ 
    if ($destinationName == '') 
    { 
    $destinationName = $file['name']; 
    } 
    $destinationFile = $destinationDir . '/' . $destinationName; 

    if (move_uploaded_file($file['tmp_name'], $destinationFile)) 
    { 
    if ($secure) 
    { 
     chmod($destinationFile, 0644); // without execution permissions if it is possible 
    } 
    $ret = true; 
    } 
} 

return $ret; 
    } 

1:我怎样才能在上传到服务器时重命名文件?

2:如果文件名存在,那么如何自动重命名?

在此先感谢

回答

1

使用file_exists这种情况:

public static function upload(&$file, $destinationDir = "", $destinationName = "", $secure = true){ 
$ret = false; 

if(isset($file['tmp_name']) && isset($file['name'])){ 
    if ($destinationName == ''){ 
    $destinationName = md5($file['name']); 
    } 
    $destinationFile = $destinationDir.'/'.$destinationName; 

    if(file_exists($destinationFile)){ 
     // Change the destination file name if it exists 
     $destinationFile = $destinationDir.'/'.md5($destinationName.rand()); 
    } 

    if (move_uploaded_file($file['tmp_name'], $destinationFile)){ 
    if($secure){ 
     chmod($destinationFile, 0644); // without execution permissions if it is possible 
    } 
    $ret = true; 
    } 
} 

注:
move_uploaded_file - 移动上传的文件,以结构化这样

bool move_uploaded_file (string $filename , string $destination) 
一个新的位置

$destination参数中给出了新上传文件的名称。将您的文件命名为独特的东西。无论如何,所以不要担心这个

+0

感谢您的回答,请问如何获取path_filename?其实现在问题已经解决,但仍然path_filename将被保存为真正的文件名称后不会改变。 –

+0

只需加密即可。看看我编辑的答案 –