Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

readdir and scandir

Tags:

php

On my localhost machine, I have two files :

IMG_9029_измен.размер.jpg and słońce32 opalenier1.jpg

I want to get filename of themes by scandir() or readdir() but can't get extractly filename. They are like this:

IMG_9029_?????.??????.jpg  and slonce32 opalenier.jpg

Window XP SP3, php5.2.12 

How I can get filename like IMG_9029_измен.размер.jpg and słońce32 opalenier1.jpg ?

like image 847
Chameron Avatar asked Aug 23 '10 04:08

Chameron


People also ask

What is opendir and readdir?

opendir() takes one parameter, which is the directory you wish to access. If it opens the directory successfully, it returns a handle to the directory, which you should store away somewhere for later use. Readdir() takes one parameter, which is the handle that opendir() returned.

What is Scandir?

The scandir() function returns an array of files and directories of the specified directory.

What does Readdir return?

The readdir() function returns a pointer to a structure representing the directory entry at the current position in the directory stream specified by the argument dirp, and positions the directory stream at the next entry. It returns a null pointer upon reaching the end of the directory stream.

What does Opendir return in C?

Returned value. If successful, opendir() returns a pointer to a DIR object. This object describes the directory and is used in subsequent operations on the directory, in the same way that FILE objects are used in file I/O operations.


2 Answers

I assume that your php encoding is utf-8.

$files = scandir($dirname);
foreach ($files as $file) {
    $filename = iconv ( "windows-1251" , "UTF-8", $file );
    echo $filename ."\n";
}

It should work for first file, but I don't know which encoding use for second file.

The main problem is that php 5 don't support utf-8 for file operations. It is internally ansi. So it reads file names using ansi api (only 8bit encoding).

like image 58
Tomas Avatar answered Oct 21 '22 01:10

Tomas


The names are probably right, but you need to set the encoding of your page to UTF-8.

Add this to the header section of your pages:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 

Then convert your strings to UTF8 so the special characters show up correctly.

I made a function that does it, it's called Encoding::toUTF8().

Usage:

$utf8_string = Encoding::toUTF8($utf8_or_latin1_or_mixed_string);

Download:

http://dl.dropbox.com/u/186012/PHP/forceUTF8.zip

like image 22
Sebastián Grignoli Avatar answered Oct 21 '22 02:10

Sebastián Grignoli