Php - rename images before upload

How to add rename function? Rename images only if same file name exists like image.jpg, image1.jpg …

function niceURL($string){ //fix file names
	$que = array( 'ü','õ','ö','ä',' ','&' );
	$por = array( 'u','o','o','a','-','-' );
	return strtolower( str_replace( $que,$por,$string ) );
}

foreach($_FILES['file']['tmp_name'] as $key => $value) {
        $tempFile = $_FILES['file']['tmp_name'][$key];
        $targetFile =  $UploadFolder."/".niceURL($_FILES['file']['name'][$key]);
        move_uploaded_file($tempFile,$targetFile);
}

You change it here when you do the move.

check if the file exists, if it does change it. However, I would give every file uploaded a different name to begin with and just record what the new name is, what the old name was, and where it is in a database.

Thank you!

I manage to work like this using date not number in filename.
If i want numbers like: image_1, image_2…, i need to check agan if next failname is taken.

function niceURL($string){
    	$que = array( 'ü','õ','ö','ä',' ','&' );
    	$por = array( 'u','o','o','a','-','-' );
    	return strtolower( str_replace( $que,$por,$string ) );
}

function editfilename($fname){
    	if (file_exists($GLOBALS['UploadFolder'].'/'.$fname)){
    		$data = explode('.', $fname);
    		return $data[0].date('_His').'.'.$data[1];
    	}else{
    		return $fname;
    	}
}
     
foreach($_FILES['file']['tmp_name'] as $key => $value) {
            $tempFile = $_FILES['file']['tmp_name'][$key];
            $targetFile =  $UploadFolder."/".editfilename(niceURL($_FILES['file']['name'][$key]));
            move_uploaded_file($tempFile,$targetFile);
}

I use the following function to generate filenames, each one being unique. It’s robust in that it handles cases where there is no .ext. It will return filenames such as “filename.ext”, “filename(1).ext”, “filename(2).ext” etc.

function uniquename($pathname)
{
    $inc = 1;
    $firstname = '';
    while(file_exists($pathname))
    {
        $parts = pathinfo($pathname);
        $ext = $parts['extension'];
        if($firstname == '')
            $firstname = $parts['filename'];
        $pathname = sprintf("%s/%s(%d)%s%s", $parts['dirname'], $firstname, $inc++, ($ext == '' ? '' : '.'), $ext);
    }
    return($pathname);
}
Sponsor our Newsletter | Privacy Policy | Terms of Service