Replace special characters before the file is uplo

2019-02-08 04:09发布

I was wondering if it is possible to change the name of the file to be uploaded. I mean what I am trying to do is that, the user uploads a file which may have some special characters like special characters in some European languages.

What I am planning to do is that before using the move_uploaded_file command is it possible to change/preg_replace the special characters with normal characters, so that the file is uploaded and stored with the new name which has only normal characters.

5条回答
beautiful°
2楼-- · 2019-02-08 04:45

try to use this bro

   $result = iconv("UTF-8", "ASCII//TRANSLIT", $text);

to know more visit how to replace special characters with the ones they're based on in PHP?

查看更多
Summer. ? 凉城
3楼-- · 2019-02-08 04:50

Also you can use a function for special characters like this:

function safename($theValue)
{
    $_trSpec = array(
        'Ç' => 'C', 
        'Ğ' => 'G', 
        'İ' => 'I',
        'Ö' => 'O', 
        'Ş' => 'S', 
        'Ü' => 'U',
        'ç' => 'c', 
        'ğ' => 'g', 
        'ı' => 'i',
        'i' => 'i',
        'ö' => 'o', 
        'ş' => 's', 
        'ü' => 'u',
    );
    $enChars = array_values($_trSpec);
    $trChars = array_keys($_trSpec);
    $theValue = str_replace($trChars, $enChars, $theValue); 
    $theValue=preg_replace("@[^A-Za-z0-9\-_.\/]+@i","-",$theValue);
    $theValue=strtolower($theValue);
    return $theValue;
}

Be carefull about allow . for file extension.

And then change your original temp file name,

$tempFile = $_FILES['Filedata']['tmp_name'];
$targetFile = safename($targetFile);

$location = 'path/to/dir/';
move_uploaded_file($_FILES["file"]["tmp_name"], $location.$targetFile);
查看更多
\"骚年 ilove
4楼-- · 2019-02-08 04:51

You could do it like this, write a simple function strip_special_chars() to replace characters you want in a string

$tmp_name = $_FILES["file"]["tmp_name"];
$name = strip_special_chars($tmp_name);
move_uploaded_file($name, "path/to/dir/");
查看更多
再贱就再见
5楼-- · 2019-02-08 05:04

You can get the original filename for an uploaded file from $_FILES, and you can create your "special" version by replacing characters in it with strtr (which sounds as the best match for this case), str_replace, preg_replace or any other string processing function.

The best approach depends on what exactly you want to do.

查看更多
该账号已被封号
6楼-- · 2019-02-08 05:06
// Get the original file name from $_FILES
$file_name= $_FILES['file']['name'];

// Remove any characters you don't want
// The below code will remove anything that is not a-z, 0-9 or a dot.
$file_name = preg_replace("/[^a-zA-Z0-9.]/", "", $file_name);

// Get the location of the folder to upload into
$location = 'path/to/dir/';

// Use move_uploaded_file()
move_uploaded_file($_FILES["file"]["tmp_name"], $location.$file_name);
查看更多
登录 后发表回答