Thursday, 2 May 2013

Upload files and rename


We have faced some issue like file duplication or replacing image or file with same name when using upload function. 

Here is the tested script which checks exists files with being uploaded file and check if the same name is exists or not. If any file with the same name exist in your UPLOAD directory then it will rename your files with numeric post fix, that escape you from overwritten existing files. Hope it helps


<form name="form1" method="post" action="" enctype="multipart/form-data">
<label>Upload files : </label><input type="file" name="file" value="" />
<input type="submit" name="submit" value="submit" />
</form>

<?php


$path = "upload/";
if($_POST['submit'])

{
$name = $_FILES['file']['name'];
$name = if_exist_rename($name,$path);
if(move_uploaded_file($_FILES['file']['tmp_name'],"upload/".$name))
    {

        echo "File uploaded successfully";
    }else
    {
        echo "Problem in Upload";
    }

}

function if_exist_rename($name,$path)   
{
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($name, PATHINFO_EXTENSION);

$i = 1;
while(file_exists($path.$actual_name.".".$extension))
    {          
       $actual_name = (string)$original_name.'-'.$i;
       $name = $actual_name.".".$extension;
       $i++;
    }
    return $name;
}
?>

No comments:

Post a Comment