在使用PHP上传文件之前替换特殊字符


Replace special characters before the file is uploaded using PHP

我想知道是否可以更改要上传的文件的名称。我的意思是,我想做的是,用户上传一个文件,其中可能有一些特殊字符,比如一些欧洲语言中的特殊字符。

我计划做的是,在使用move_uploaded_file命令之前,可以用普通字符更改/preg_replace特殊字符,这样文件就可以用只有普通字符的新名称上传和存储。

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

尝试使用此bro

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

要了解更多信息,请访问如何用他们';是基于PHP的吗?

您可以从$_FILES获取上传文件的原始文件名,并可以通过将其中的字符替换为strtr(在这种情况下听起来最匹配)、str_replacepreg_replace或任何其他字符串处理函数来创建"特殊"版本。

最佳方法取决于您想要做什么

您可以这样做,编写一个简单的函数strip_special_chars()来替换字符串中所需的字符

$tmp_name = $_FILES["file"]["tmp_name"];
$name = strip_special_chars($tmp_name);
move_uploaded_file($name, "path/to/dir/");

您还可以为特殊字符使用函数,例如:

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

小心允许。用于文件扩展名。

然后更改您的原始临时文件名

$tempFile = $_FILES['Filedata']['tmp_name'];
$targetFile = safename($targetFile);
$location = 'path/to/dir/';
move_uploaded_file($_FILES["file"]["tmp_name"], $location.$targetFile);