如何用空格和特殊字符重命名上传的图像?

How to rename uploaded images with spaces and special characters?

所以在这里我将分享mu clean string函数和我上传图片的代码。如果图像文件的名称例如“credi-- @% sdfdsf..####tcard.jpg”,我需要帮助使用该功能在上传前清理文件名我希望在上传前清理它我有一个干净的字符串函数

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

这是我的上传图片代码

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;
}

谁能帮我在上传前清理图片名称?

非常感谢

使用 PHP 时,您无法在上传 之前修改文件名 ,因为 PHP 在服务器上运行。 Javascript 也无法重命名 client-side 上的文件,尽管它可以发送与正在上传的文件不同的名称!从这段代码的外观来看,您想要做的是在上传后但在保存和记录到数据库之前修改文件名。

在您的原始代码中,我认为您可以更改

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

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

但是你可以尝试这样的事情:

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) );
}