2012-10-20 24 views
0

Hye夥計們,我已經創建了jquery ajax文件上傳器,但是我有一個問題,它是服務器端,它將覆蓋任何具有相同名稱的文件並且我將生成一個隨機數,這應該是一個又一個不同的,但這樣對我上傳的代碼是php fileuploader basenam

<?php 
$target_path = "/var/www/vhosts/grubber.co.nz/httpdocs/developer/_social_development/uploads/blog/"; 
$target_path = $target_path . basename($_FILES['img']['name']); 


if (file_exists($target_path)) { 
    echo "The file $filename exists"; 
    $target_path = "/var/www/vhosts/grubber.co.nz/httpdocs/developer/_social_development/uploads/blog/" . basename($_FILES['img']['name']); 
} else { 
    echo "The file $filename does not exist"; 
} 


if(move_uploaded_file($_FILES['img']['tmp_name'], $target_path)) { 
    echo "The file ". basename($_FILES['img']['name']). 
    " has been uploaded"; 
} else{ 
    echo "There was an error uploading the file, please try again!"; 
} 
?> 

問題,我希望它檢查文件是否exsits,如果它產生一個隨機數,並把它添加到名字?如果不只是繼續並寫入文件。

回答

3

一種解決方案可能是預先給文件名添加一些唯一的編號。

您可以使用uniqid()函數。 http://php.net/manual/en/function.uniqid.php

<?php 
$target_path = "/var/www/vhosts/grubber.co.nz/httpdocs/developer/_social_development/uploads/blog/"; 
$target_path = $target_path . basename($_FILES['img']['name']); 


if (file_exists($target_path)) { 
    echo "The file $filename exists"; 
    $target_path = "/var/www/vhosts/grubber.co.nz/httpdocs/developer/_social_development/uploads/blog/" .uniqid().basename($_FILES['img']['name']); 
} else { 
    echo "The file $filename does not exist"; 
} 


if(move_uploaded_file($_FILES['img']['tmp_name'], $target_path)) { 
    echo "The file ".basename($_FILES['img']['name']). 
    " has been uploaded"; 
} else{ 
    echo "There was an error uploading the file, please try again!"; 
} 
?> 
+0

那不行它只是彈出一個錯誤「的文件存在 致命錯誤:調用到/var/www/vhosts/grubber.co.nz/httpdocs/developer未定義功能UNIQUEID() /_social_development/json/uploadblog.php on line 8「 – ryanc1256

+0

糟糕,錯字錯誤,請使用uniqid();代替。 –

+0

haha​​haha,謝謝你的工作:-D – ryanc1256