'How to rename uploaded images with spaces and special characters?

So here i will share mu clean string function and my upload image code. i need help in using the function to clean the file name before being uploaded if the image file has names for example "credi-- @% sdfdsf..####tcard.jpg" i wish to clean it before upload for which i have a clean string function

function cleanStr($string) {
   $string = str_replace(' ', '-', $string);
   $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
   return preg_replace('/-+/', '-', $string); 
}

and here is my upload image code

if(isset($_POST['upload'])) {
    $countfiles = count($_FILES['files']['name']);
    $query = "INSERT INTO images (post_id,name,image) VALUES(?,?,?)";
    $statement = $db->prepare($query);
    for($i = 0; $i < $countfiles; $i++) {
        $filename = date('Y-m-d-his').'-'.$_FILES['files']['name'][$i];
        $target_file = 'uploads/documents/'.$filename;
        $file_extension = pathinfo(
            $target_file, PATHINFO_EXTENSION);              
        $file_extension = strtolower($file_extension);
        $valid_extension = array("png","jpeg","jpg");       
        if(in_array($file_extension, $valid_extension)) {
            if(move_uploaded_file($_FILES['files']['tmp_name'][$i],$target_file)){ 
                $statement->execute(array($_GET['id'],$filename,$target_file));
            }
        }
    }
header('Location: result.php?id='.$_GET['id'].'&action=UPLOADED');
exit;
}

can someone help me out cleaning the image name before being uploaded?

thanks alot



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source