basename、pathinfo相关

我之前有两篇笔记,分别写了php里面timezone的设置php乱码相关的知识

在使用php函数basename的时候,遇到问题了,中文的文件名出不来。

这个问题,还是在使用菜鸟在线编辑器的时候用到的

比如说,我在它里面写上代码,但结果却不如人意。

php-basename

如上图所示,我想要用basename输出一个文件的名字,但是它却没有输出中文名,只输出了后缀。

该用pathinfo也有同样的问题

php-pathinfo

这到底是怎么回事儿?

我有使用php cli形式,在我自己的机器上试了一下。

<?php 
$file = '/home/users/nemo/dir/中文.xls';
$info = pathinfo($file);
var_dump($info);
?> 

结果如下图。没有问题啊

array(4) {
  ["dirname"]=>
  string(20) "/home/users/nemo/dir"
  ["basename"]=>
  string(10) "中文.xls"
  ["extension"]=>
  string(3) "xls"
  ["filename"]=>
  string(6) "中文"
}

不使用php命令行,改成在浏览器里面显示,看一下是怎么回事儿

echo '--test show english--';
echo "\n";
echo '--test show 中文--';
echo "\n";
header('Content-Type: text/plain;');
$file = '/home/users/nemo/dir/中文.xls';
$info = pathinfo($file);
var_dump($info);

header里面不设置charset,在浏览器里面显示是

php-pathinfo-in-my-browser

联想到上一篇笔记里面讲的乱码相关的知识。如果在代码里面的header设置charset,那么浏览器的显示效果如下:

echo '--test show english--';
echo "\n";
echo '--test show 中文--';
echo "\n";
header('Content-Type: text/plain; charset=utf-8');
$file = '/home/users/nemo/dir/中文.xls';
$info = pathinfo($file);
var_dump($info);


php官网查一下是怎么说basenamepathinfo怎么说的。

Note:

basename() is locale aware, so for it to see the correct basename with multibyte character paths, the matching locale must be set using the setlocale() function.

pathinfo() is locale aware, so for it to parse a path containing multibyte characters correctly, the matching locale must be set using the setlocale() function.

原来这个方法和本地化有关,再来看看setlocale()这个方法

setlocale(LC_ALL, 'en_US.UTF-8');表示设置地区为US English,并且使用UTF-8编码

假如说上面那段代码,不在header里面设置charset,但是在代码里面setlocale()会怎么样?

echo '--test show english--';
echo "\n";
echo '--test show 中文--';
echo "\n";
setlocale(LC_ALL, 'en_US.UTF-8');
$file = '/home/users/nemo/dir/中文.xls';
$info = pathinfo($file);
var_dump($info);

setlocale(LC_ALL, 'en_US.UTF-8');换成setlocale(LC_ALL, 'zh_CN.UTF-8');,或者编码换成GBKISO-9558-1都没什么用,显示在浏览器里面都是乱码的

乱码


还有一个需要注意的地方,假如说你有一个文件夹,里面的文件是由别人来上传的,其实你并不知道文件会叫什么名字,php代码里面使用basename或者pathinfo来读取这个文件的名字。

如果对方是在windows平台上传文件到服务器,那么可能会出现乱码问题。


在使用basenamepathinfo的时候要长个心眼儿,注意一下是否能正确得出文件名。

Show Comments