This code get content file txt:
$str = "c:\\\\表\\t.txt";
$con=file_get_contents( $str);
echo $con;
File exist in folder:
Result: show error:
Warning: file_get_contents(c:\表\t.txt): failed to open stream: No such file or directory in C:\xampp\htdocs\direction\test.php on line 6
Why is file_get_contents() not working?
How read content of path c:\表\t.txt?
Try to use urlencode to encode your directory name:
$str = 'c:\\'.urlencode('表').'\t.txt';
$con=file_get_contents( $str);
echo $con;
This is described here in detail.
EDIT
Assuming you're using UTF-8 encoded source files, you could also try one of the following
$str = 'c:\\'.urlencode(mb_convert_encoding('表', 'UTF-16', 'UTF-8')).'\t.txt';
// or just
$str = 'c:\\'.mb_convert_encoding('表', 'UTF-16', 'UTF-8').'\t.txt';
As far as I know newer (> FAT32) Microsoft filesystems use UTF-16 encoding. But this will make your solution fail on other (e.g. Linux) filesystems.
EDIT 2
You can also try to convert your UTF-8 filename into a different encoding such as SJIS, SJIS-win, SJIS-2004, JIS, EUC-JP, eucJP-win, EUC-JP-2004, CP932, JIS-ms or the like. But I'm not an expert in east asian character encodings - so treat that information with caution.
try this
<?PHP
$con=file_get_contents('./表/t.txt', true);
$con=file_get_contents('./表/t.txt',FILE_USE_INCLUDE_PATH);
echo $con;
?>
Language : PHP
$results = scandir('c:\');
$result will give you all folder name inside c drive.
you can find your folder in $result array.
now you have folder name in $result and now you can go to file.
Modified :
$results = scandir('/web');
$results = "/web/$results[21]/t.txt";
$con=file_get_contents( $results);
echo $con;
Explanation :
1.) /web is the directory where is 表 folder and some other folders.
2.) $result[21] is giving me value 表 on browser i know its 表 folder.
3.) Now you have file path. Go ahead.
NOTE : If you still use Chinese character in your folder and file then you have to change your OS from window to ubuntu.
Create path based on single /
$content = file_get_contents("C:/表/t.txt");
You can read more about Filesystem here: http://php.net/manual/en/wrappers.file.php
Related
I'm trying to write a script which open the directory, scan all files (images) and displayed it on the screen, but the problem is, it contains symbols in their names and scandir can't handle it.
It's ok with the directories where no symbols are present in their names, the script works perfect, but the directories/files with the symbols in their name is a big problem.
For instance, I have a total 2 directories and all files in that directories contains the same symbols in their name. One contain "®" and the other contain "™" and every single file (image) have these symbol in their names, for example: "Right® screen452217.jpg". So, renaming the directories and files is not an option, this would take too much time.
Maybe is there a better way, but I do it directly from url on screen with $_GET. It's on a local server for now, I'm working in VertrigoServ WAMP server and the script then look like:
http://127.0.0.1/screenshots/index.php?page=Rights®
http://127.0.0.1/screenshots/index.php?page=Trade%20Marks™
$url = "screens/".$_GET["page"]."";
$scan = scandir($url, SCANDIR_SORT_NONE);
$scaned = array_diff($scan, array('.', '..', 'Thumbs.db'));
foreach($scaned as $shots) {
if ($shots <> "thumbnails") {
echo "<li>".PHP_EOL.
" <img width=\"253\" height=\"158\" src=\"".$url."\\".$shots."\"".
" alt=\"".$shots."\" title=\"".$shots."\".
" </li>".PHP_EOL.PHP_EOL;
}
}
scandir reports these errors:
The system cannot find the file specified. (code: 2)
failed to open dir: No such file or directory
No such file or directory
array_diff reports this error:
Argument #1 is not an array
and finally foreach report:
Invalid argument supplied for foreach()
I also tried to change encoding with mb_convert_encoding() and iconv(), but no luck.
My best result was after changing url, instead of using "®" or "™" I used windows-1252 ASCII Encoding Reference:
http://127.0.0.1/screenshots/index.php?page=Rights%AE
http://127.0.0.1/screenshots/index.php?page=Trade%20Marks%99
Then everything passed with no error, but instead of showing images, the "img src" looks like:
screens/Rights�\Right�452217.jpg
which is still problem, because images are not displayed. I like to stick with scandir, because I already have done the page, but I can't pass through this problems with symbols. Can you help me, please ?
It was actually simpler than I thought. Problem was, that the directory was already with symbols in their names, so I must change that to Windows-1252 like this:
$page = $_GET["page"];
if (strpos($page, '®')) {$page = str_replace('®', '%AE', $page);}
if (strpos($page, '™')) {$page = str_replace('™', '%99', $page);}
Then the URLs change from:
http://127.0.0.1/screenshots/index.php?page=Rights®
http://127.0.0.1/screenshots/index.php?page=Trade%20Marks™
To:
http://127.0.0.1/screenshots/index.php?page=Rights%AE
http://127.0.0.1/screenshots/index.php?page=Trade%20Marks%99
Then it was simple, just add encoding after scandir and one in foreach:
$url = "screens/".$_GET["page"]."";
$scan = scandir($url, SCANDIR_SORT_NONE);
$scaned = array_diff($scan, array('.', '..', 'Thumbs.db'));
$url = iconv("windows-1252", "UTF-8", $screen_uplay);
foreach($scaned as $shots) {
if ($shots <> "thumbnails") {
$shots = iconv("windows-1252", "UTF-8", $shots);
echo "<li>".PHP_EOL.
" <img width=\"253\" height=\"158\" src=\"".$url."\\".$shots."\"".
" alt=\"".$shots."\" title=\"".$shots."\".
" </li>".PHP_EOL.PHP_EOL;
}
}
Simple as that. Maybe is there a better way, but this is working for me and I'm ok with that.
I want to save a file to Windows using Japanese characters in the filename.
The PHP file is saved with UTF-8 encoding
<?php
$oldfile = "test.txt";
$newfile = "日本語.txt";
copy($oldfile,$newfile);
?>
The file copies, but appears in Windows as
日本語.txt
How do I make it save as
日本語.txt
?
I have ended up using the php-wfio extension from https://github.com/kenjiuno/php-wfio
After putting php_wfio.dll into php\ext folder and enabling the extension, I prefixed the filenames with wfio:// (both need to be prefixed or you get a Cannot rename a file across wrapper types error)
My test code ends up looking like
<?php
$oldfile = "wfio://test.txt";
$newfile = "wfio://日本語.txt";
copy($oldfile,$newfile);
?>
and the file gets saved in Windows as 日本語.txt which is what I was looking for
Starting with PHP 7.1, i would link you to this answer https://stackoverflow.com/a/38466772/3358424 . Unfortunately, the most of the recommendations are not valid, that are listed in the answer that strives to be the only correct one. Like "just urlencode the filename" or "FS expects iso-8859-1", etc. are terribly wrong assumptions that misinform people. That can work by luck but are only valid for US or almost western codepages, but are otherwise just wrong. PHP 7.1 + default_charset=UTF-8 is what you want. With earlier PHP versions, wfio or wrappers to ext/com_dotnet might be indeed helpful.
Thanks.
I need to convert a CSV file to UTF-8 and rename it using a PHP script.
The following code worked on my PC but now i need to do this on a server as a CRON task
iconv -f UTF-16LE -t UTF-8 OLD-FILE.csv > NEW-FILE.csv
Anyone know the equivalent in PHP. Thanks a lot.
A simple method would be to load the CSV file to a string using this command:
http://php.net/manual/en/function.file-get-contents.php
Then you can UTF-8 Encode the string using this command:
http://php.net/manual/en/function.utf8-encode.php
Finally write the string to a file using file_put_contents.
Finished code could look like this:
$file_data = file_get_contents('/my/path/to/file.csv');
$utf8_file_data = utf8_encode($file_data);
$new_file_name = '/my/path/to/new_file.csv';
file_put_contents($new_file_name , $utf8_file_data );
Make sure the web server has the correct permissions to both read and write to appropriate locations.
Here is the link to file_put_contents():
http://php.net/manual/en/function.file-put-contents.php
So here is the solution I found thanks to our brainstorming:
<?php
$file_data = file_get_contents('/home/MYFILE.csv');
//$utf8_file_data = utf8_encode($file_data);
$utf8_file_data = mb_convert_encoding($file_data, "UTF-8", "UTF-16LE");
//$utf8_file_data = iconv("UTF-16LE","UTF-8",$file_data);
$new_file_name = '/home/MYFILE_NEW.csv';
file_put_contents($new_file_name , $utf8_file_data );
?>
The only pb is that the output size is twice as big as the input. If I use ICONV on my PC it is HALF the size...
If anyone knows I'd like to hear why.
if iconv is available you can use the PHP equivalent: http://php.net/manual/en/function.iconv.php note that this takes a string, you will need to read in the file http://php.net/manual/en/function.fread.php and then write it out http://php.net/manual/en/function.file-put-contents.php but this approach may be slower and for big files, it will require to load the file to memory.
Currently I am trying to check with PHP if a file exists. The current file I am trying to check if it exists has an apostrophe in it, the file is called:13067-AP-03 A - Situation projetée.pdf.
The code I use to check if the file exist is:
$filename = 'C:/13067-AP-03 A - Situation projetée.pdf';
if (file_exists($filename))
{
echo "The file exists";
} else
{
echo "The file does not exist";
}
The problem that I am facing right now is that whenever I try to check if the file exists I get the message it doesn't exist. If I continue to remove the é I get the message that the file does exist.
It looks that PHP somehow doesn't recognize the file if it has a apostrophe in it. I tried the following:
urlencode($filename);
addslashes($filename);
utf8_encode($filename);
None of which worked. I also tried:
setlocale(LC_ALL, "en_US.utf8");
Maybe worth noticing is that when I get the filename straight from PHP I get the following:
13067-AP-03 A - Situation projet�e.pdf
I have to do the following to have the filename displayed correctly:
$filename = iconv( "CP437", 'UTF-8', $filename);
I was wondering if someone had the same problem before and could help me out with this one. All help is greatly appreciated.
For those who are interested, the script runs on a windows machine.
Strangely this worked: I copied all the source code from Sublime Text 3 to notepad. I proceeded to save the source code in notepad by overwriting the PHP file.
Now when I check to see if the file exists it shows the following filename that exists:
13067-AP-03 A - Situation projet�e.pdf
The only problem that I am facing right now is that I want to download the file using file_get_contents. But file_get_contents doesnt interpet the � as an apostrophe.
I think it's a problem of the PHP under Windows. I downloaded a Windows binary copy to my Windows who's in Japanese and successfully reproduced your problem.
According to https://bugs.php.net/bug.php?id=47096
So, if you have a generic name of a file (along with its path) as a Unicode string $u (for example UTF-8 encoded) and you want to try to save it with that name under Windows, you must first check the current locale calling setlocale(LC_CTYPE, 0) to retrieve the current code page, then you must convert $u to an array of bytes according to the code page; if one or more code points have no counterpart in the current code page, the file cannot be saved with that name from PHP. Dot.
My code page is CP932, which you can see yours by running chcp in cmd.
So the code is expected to be:
$filename='C:\Users\Frederick\Desktop\13067-AP-03 A - Situation projetée.pdf';
$filename=mb_convert_encoding($filename, 'CP932', 'UTF-8');
var_dump($filename);
var_dump(file_exists($filename));
But this won't work! Why? Because CP932 doesn't contain the character of é!
According to https://msdn.microsoft.com/en-us/library/windows/desktop/dd317748%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
NTFS stores file names in Unicode. In contrast, the older FAT12, FAT16, and FAT32 file systems use the OEM character set.
Windows itself uses UTF-16LE, which is called Unicode by Microsoft, to save its file names. But PHP doesn't support a UTF-16LE encoded file name.
In conclusion, it's a pity that I cannot find a way to solve the problem rather than escaping all those characters when naming the files if you work on Windows. And I also do not think that the team of PHP will solve the problem in the future.
Make sure that your text editor is saving the file as "UTF-8 without BOM"
BOM is the Byte Order Mark, two bytes placed at the start of the file which allow software reading the file to determine if it has been saved as little-endian or big-endian, however the PHP interpreter cannot interpret these characters and so you must save the file without the byte order mark.
Try this on start of your php file:
<?php
header('Content-Type: text/html; charset=utf-8');
?>
This question already has answers here:
PHP - Upload utf-8 filename
(9 answers)
UTF-8 all the way through
(13 answers)
Closed 4 months ago.
I have this home made app that allows multiple file uploads, I pass the files to php with AJAX, create new dir with php, move there uploaded files and save the dir location to database. Then to see the files I run listing of the directory location saved in the db.
The problem is that files come from all around the world so very often they have some non latin characters like for example ü. When I echo the filename in php names appear correctly even when they have names written in Arabic, yet they are being saved on the server with encoded names as for example ü in place of ü. When I list the files from directory I can see the name ü.txt insted of ü.txt but when I click on it server returns error object not found (since on the server it is saved as ü.txt and it reads the link as ü.txt).
I tried some of the suggested solutions as for example using iconv, but the filenames are still being saved the same way.
I could swear the problem wasn't present when the web app was hosted on linux, but at the moment I am not so sure about it anymore. Right now I temporarily run it on xampp (on Windows) and it seems like filenames are saved using windows-1252 encoding (default Windows' encoding on the server). Is it default Windows encoding related problem?
To be honest I do not know how to approach that problem and I would appreciate any help. Should I keep on trying to save the files in different character encoding or would it be better to approach it different way and change the manner of listing the already saved and encoded files?
EDIT. According to the (finally) closed bug report it was fixed in php 7.1.
In the end I solved it with the following approach:
When uploading the files I urlencode the names with rawurlencode()
When fetching the files from server they are obviously URL encoded so I use urldecode($filename) to print correct names
Links in a href are automatically translated, so for example "%20" becomes a " " and URL ends up being incorrect since it links to incorrect filename. I decided to encode them back and print them ending up with something like this: print $dirReceived.rawurlencode($file); ($dirReceived is the directory where received files are stored, defined earlier in the code)
I also added download attribute with urldecode($filename) to save the file with UTF-8 name when needed.
Thanks to this I have files saved on the server with url encoded names. Can open them in browser (very important as most of them are *.pdf) and can download them with correct name which lets me upload and download even files with names written in Arabic, Cyrillic, etc.
So far I tested it and looks good. I am thinking of implementing it in production code. Any concerns/thoughts on it?
EDIT.
Since there are no objections I select my answer as the one that solved my problem. After doing some testing everything looks good on client and server side. When saving the files on server they are URL encoded, when downloading them they are decoded and saved with correct names.
At the beginning I was using the code:
for($i=0;$i<count($_FILES['file']['name']);$i++)
{
move_uploaded_file($_FILES['file']['tmp_name'][$i],
"../filepath/" . $_FILES['file']['name'][$i]);
}
This method caused the problem upon saving file and replaced every UTF-8 special character with cp1252 encoded one (ü saved as ü etc.), so I added one line and replaced that code with the following:
for($i=0;$i<count($_FILES['file']['name']);$i++)
{
$fname= rawurlencode($_FILES['file']['name'][$i]);
move_uploaded_file($_FILES['file']['tmp_name'][$i],
"../filepath/" . $fname);
}
This allows me to save any filename on server using URL encoding (% and two hexadecimals) which is compatible with both cp1252 and UTF-8.
To list the saved files I use filepaths I have saved in DB and list them for files. I was using the following code:
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if(is_file($dir . $file)){
echo "<li><a href='".$dir.$file."' download='".$file ."'>".$file."</a></li><br />";
}
}
closedir($dh);
}
}
Since URL encoded filenames were decoded automatically I changed it to:
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if(is_file($dir . $file)){
echo "<li><a href='";
print $dir.rawurlencode($file);
echo "' download='" . urldecode($file) ."'>".urldecode($file)."</a></li><br />";
}
}
closedir($dh);
}
}
I don't know if this is the best way to solve it but works perfectly, also I am aware that it is generally a good practice not to use php to generate html tags but at the moment I have some critical bugs that need addressing so first that and then I'll have to work on the appearance of the code itself.
EDIT2
Also the great thing is I do not have to change names of the already uploaded files which in my case is a big advantage.
Are you using $_FILES['upfile']['name'] to name the file? That could create your problem.
How about using GNU Recode?
$fileName = recode_string('latin1',$_FILES['upfile']['name']);
Syntax:
recode_string(string recode type,string $string)
Valid Character sets: http://www.faqs.org/rfcs/rfc1345.html
Somehow you must validate the characters in the uploaded file name.
You could also try sprintf. The formatted string characters can be unpredictable, but will probably work.
$fileName = pathinfo($_FILES['upfile']['name'], PATHINFO_FILENAME);
$fileName = sprintf('./uploads/%s',$fileName);
When you save the file name use
$fileName = mysqli_real_escape_string($fileName)