Replace special characters before the file is uploaded using PHP

三世轮回 提交于 2019-11-30 14:44:35

问题


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.


回答1:


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



回答2:


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?




回答3:


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.




回答4:


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:


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


来源:https://stackoverflow.com/questions/9838994/replace-special-characters-before-the-file-is-uploaded-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!