解决file_get_contents遇到中文文件名无法打开问题
利用file_get_contents打开文件或采集远程服务器文件如果文名或url中碰到汉字中文那么会出现failed to open stream:Lnvalid argument in错误。
今天遇到一个很棘手的问题,客户用ftp向服务器传了一个文件,但是却无法被程序识别.查看代码后,没有发现问题,最后重演流程发现,客户上传的文件是中文命名的.于是小做测试发现,file_get_contents函数尽然不支持中文文件名文件.
原有代码如下:
$filename='哈.txt';
echo file_get_contents('./'.$filename);
执行以后显示结果:
悲剧开始.
之后试了不少判断方法,显示怀疑是不是编码问题,文件编码,代码编码一遍遍的排查,可是都是很匹配的啊.
之后查了相关资料却没有找到,于是google了一下发现有人遇到这个问题,说是系统编码的问题,于是开始对文件名进行转码.
文件用的是utf-8编码,但是系统默认为gbk.所以先把文件名转换gbk然后再读取.
$filename='哈.txt';
$filename=iconv('utf-8','gb2312',$filename);
//echo file_get_contents(mb_convert_encoding('./哈.txt', 'gbk', 'utf-8')); (另一种方法)
echo file_get_contents('./'.$filename);
测试结果:
读取成功.
OK,大功告成.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.