我需要编写代码,以便在已经上传具有相同名称的文件时重命名文件。例如,如果您上传“internet.jpg”但该文件已存在于服务器端和bd中,则系统重命名为“internet_2.jpg”
我的代码:
<?php
mysql_connect("localhost", "user", "user") or die(mysql_error()) ;
mysql_select_db("view") or die(mysql_error()) ;
if ($_FILES["imagen"]["error"] > 0){
echo "ha ocurrido un error";
} else {
$permitidos = array("image/jpg", "image/jpeg", "image/gif", "image/png");
$limite_kb = 100;
if (in_array($_FILES['imagen']['type'], $permitidos) && $_FILES['imagen']['size'] <= $limite_kb * 1024){
$ruta = "./image/" . $_FILES['imagen']['name'];
$resultado = @move_uploaded_file($_FILES["imagen"]["tmp_name"], $ruta);
if ($resultado){
$nombre = $_FILES['imagen']['name'];
@mysql_query("UPDATE product SET image='data/$nombre' Where id=55") ;
echo "la imagen ha sido actualizada exitosamente";
echo "
";
} else {
echo "ocurrio un error al mover el archivo.";
}
} else {
echo "archivo no permitido, es tipo de archivo prohibido o excede el tamano de $limite_kb Kilobytes";
}
}
?>
----------------------感谢------------------------ -----
thank you very much Farhan Ihsas, your code worked perfect!
I just change two lines
$new_name = $rand . '_'. $dotName ;
and
@mysql_query("UPDATE product SET image='./image/$new_name' Where product_id=55") ;
Thanks for such a quick response!
thank you both ( Farhan Ihsas and Kieran )
答案 0 :(得分:0)
您想要使用file_exists和move_uploaded_file
的组合E.g。
function setFilename($file, $count = 1) {
if (file_exists($file)) {
return setFilename($file, $count++);
} else {
$path_parts = pathinfo($file);
move_uploaded_file($file, "{$fileData['dirname']}/{$path_parts['filename']}_{$count}.{$path_parts['extension']}";
}
}
答案 1 :(得分:0)
我假设您的代码没有任何错误,请找出该行并替换它。
if(in_array($_FILES['imagen']['type'],$permitidos) && $_FILES['imagen']['size'] <=$limite_kb * 1024){
$fileName = $_FILES['imagen']['name'];
$ruta = "./image/" . $fileName ;
if (file_exists($ruta)) {
$dotType = pathinfo( $fileName, PATHINFO_FILENAME);
$rand = rand(111, 2333);
$dotName = str_replace('.' . $dotType, '', $fileName) ;
$new_name = $dotName . '_' . $rand . '.'. $dotType ;
$ruta = "./image/" . $new_name;
}
$resultado = @move_uploaded_file($_FILES["imagen"]["tmp_name"], $ruta);