我不擅长php编码,有人可以帮我解决这个php上传代码。
我有上传文件的php文件到服务器工作完美但我的问题是它将取代旧文件。我不想替换旧的,例如,如果文件存在上传文件重命名(文件到file_1)。
<?php
$target_path1 = "uploads/";
/* Add the original filename to our target path. Result is "uploads/filename.extension" */
$target_path1 = $target_path1 . basename($_FILES['uploaded_file']['name']);
if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)) {
echo "The first file " . basename($_FILES['uploaded_file']['name']) . " has been uploaded.";
} else {
echo "There was an error uploading the file, please try again!";
echo "filename: " . basename($_FILES['uploaded_file']['name']);
echo "target_path: " . $target_path1;
}
?>
我将非常感谢你的帮助......
答案 0 :(得分:2)
你可以试试这个
if(!file_exists("folder/".$_FILES["file"]["name"])){
$file = "folder/".$_FILES["file"]["name"];
if(move_uploaded_file($tmp_name, $file));{
"your message"
}
} else {
$file = "your folder/01_".$_FILES["file"]["name"];
if(move_uploaded_file($tmp_name, $file));{
"your message"
}
}
你也可以使用rand()函数重命名
答案 1 :(得分:1)
使用上传文件时的if或while检查条件
if (file_exists("YOUR-FOLDER/" . $_FILES["file"]["name"])){
//code to rename your file name. Use time() or rand() etc...
}
答案 2 :(得分:0)
使用php函数isfile
检查您的文件if (!is_file('uploads/'.$_FILES['uploaded_file']['tmp_name'])) {
move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1);
}
OR 您可以使用rename
uniqueid您的文件名答案 3 :(得分:0)
我认为有两种解决方案 如果您只想要新文件名,可以在文件名末尾添加时间
if( isset($_FILES['uploaded_file']['name']) && !empty($_FILES['uploaded_file']['name']) ){
$tFile = $_FILES['uploaded_file'];
$fileName=time().$tFile['name'];
$mn_dir='your folder location'.$fileName ;
if( !@move_uploaded_file( $tFile['tmp_name'] , $mn_dir) ){
return true
}else{
return false
}
}
但如果要检查文件是否存在
if( file_exists("Your Folder/".$_FILES['uploaded_file']['name']) ){
// you can add number to file , I think you should add tile because file_1 and file_2 , ... may be exist
$tFile = $_FILES['uploaded_file'];
$fileName=time().$tFile['name'];
$mn_dir='your folder location'.$fileName ;
if( !@move_uploaded_file( $tFile['tmp_name'] , $mn_dir) ){
return true
}else{
return false
}
}else{
// upload the file
}
答案 4 :(得分:0)
制作类似
的功能public function getUniqueName($path, $name) {
$name = str_replace(" ", "_", mb_eregi_replace('\s+', ' ', $name));
$i = 0;
$uniqueName = $name;
while (file_exists("{$path}/{$uniqueName}")) {
$i++;
$uniqueName = $name . $i;
}
return $uniqueName;
}
在上传文件之前,请通过该功能获取唯一名称。希望它有所帮助。