douzhen5158 2016-01-08 16:15
浏览 18
已采纳

'Normalize'上传的文件名为php

I'm developing a french website and users in some cases needs to upload files(pdfs) and I want to save this files with their original filenames, when I try to do this, I found that PHP can't save the file with it's original filename if this filename contain letters such (é,ç,à,...) so I thought that I should replace all those french chars by their English equivalent (é->e, à a,...) I found this answer but it won't work for me ... and this is the code that doesn't work :

$unwanted_array = array('Š'=>'S', 'š'=>'s', 'Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
                        'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U',
                        'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c',
                        'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o',
                        'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y' );

$ori_fn=strtolower(basename($_FILES['userfile']['name']));
$mod_fn = strtr($ori_fn, $unwanted_array);

echo "Before : ".$ori_fn."<br>";
echo "After : ".$mod_fn."<br>";//$mod_fn same as $ori_fn nothing changed !

... this not work just when I retrieve filename string from $_FILES as the code above, but when I test with simple string as strtr("référence",$unwanted_array); then it's work normaly !

1 - What is the problem ?

2- What is the solution ?

3 - Is there better way to normalize filenames ?!

Note I mean by doesn't work : strtr doesn't change anything in received string($_FILES['userfile']['name']) !

  • 写回答

1条回答 默认 最新

  • doumu6941 2016-01-08 16:32
    关注

    strtolower doesn't work with Unicode strings, you should use mb_strtolower :

    $ori_fn = mb_strtolower(basename($_FILES['userfile']['name']), 'UTF-8');
    $mod_fn = strtr($ori_fn, $unwanted_array);
    

    However, PHP has the iconv function for this:

    $ori_fn = strtolower(basename($_FILES['userfile']['name']));
    $mod_fn = iconv('UTF8', 'ASCII//TRANSLIT', $ori_fn);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)