Ad

How To Rename Uploaded Images With Spaces And Special Characters?

- 1 answer

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

Ad

Answer

You cannot modify the filename before being uploaded when using PHP because of the fact that PHP runs on the server. Javascript cannot rename a file on the client-side either though it could send a different name with the file being uploaded! What you want to do by the looks of this code is modify the filename after upload but before being saved & logged to database.

In your original code I think you could just change

$target_file = 'uploads/documents/'.$filename;

to

$target_file = 'uploads/documents/'.cleanStr( $filename );

however you might try something like this:

if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
    $_GET['id'],
    $_FILES['files']['name']
)) {

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

    # Prepare the sql statement.
    $sql = "INSERT INTO `images` ( `post_id`, `name`, `image` ) VALUES ( ?, ?, ? )";
    $stmt = $db->prepare( $sql );

    # Establish the paths needed - one is the full, absolute path 
    # for saving and the other a relative path for display
    $basedir = __DIR__ . '/uploads/documents/'
    $displaydir = './uploads/documents/';
    
    # Permit these file extensions
    $extns = array( 'png', 'jpeg', 'jpg' ); 
    
    # iterate through all posted images
    foreach( $_FILES['files']['name'] as $i => $name ) {
    
        if( !empty( $_FILES['files']['tmp_name'][$i] ) ) {
            # we need the `tmp_name` but will modify the $name later
            $name = $_FILES['files']['name'][$i];
            $tmp  = $_FILES['files']['tmp_name'][$i];
            $error= $_FILES['files']['error'][$i];
            
            # find the file extension and file name ( without extension )
            $ext  = strtolower( pathinfo( $name, PATHINFO_EXTENSION ) );
            $name = pathinfo( $name, PATHINFO_FILENAME );
            
            # rudimentary test to see if the file is an image
            list( $width, $height, $type, $attr ) = getimagesize( $tmp );
            
            # Proceed if basic tests are passed.
            if( $error==UPLOAD_ERR_OK && isset( $width, $height, $attr ) && in_array( $ext, $extns )){
                
                # construct the save & display paths using new file name.
                $filename = sprintf('%s-%s.%s', date('Y-m-d-his'), cleanStr( $name ), $ext );
                $savepath=$basedir . $filename;
                $displaypath=$displaydir . $filename;
                
                # move the file and execute sql cmd.
                if( move_uploaded_file( $tmp, $savepath ) ){
                    $stmt->execute(array(
                        $_GET['id'],
                        $filename,
                        $displaypath
                    ));
                    
                    $count++;
                }
            }
        }
    }
    exit( header('Location: result.php?id='.$_GET['id'].'&action=UPLOADED&total='.  $count) );
}
Ad
source: stackoverflow.com
Ad