Php open directory windows

opendir — Открывает дескриптор каталога

(PHP 4, PHP 5, PHP 7)

opendir — Открывает дескриптор каталога

Описание

Открывает дескриптор каталога для последующего использования с функциями closedir() , readdir() и rewinddir() .

Список параметров

Путь к открываемому каталогу

Для описания параметра context обратитесь к разделу «Потоки».

Возвращаемые значения

Возвращает дескриптор каталога ( resource ) в случае успеха или FALSE в случае ошибки.

Если path не существует или каталог, расположенный по указанному пути, не может быть открыт вследствие правовых ограничений или ошибок файловой системы, функция opendir() вернет значение FALSE и сгенерирует сообщение PHP об ошибке уровня E_WARNING. Вы можете запретить вывод сообщения об ошибке, предварив имя функции opendir() символом ‘@’.

Список изменений

Версия Описание
5.0.0 path теперь поддерживает обертку ftp://.
4.3.0 Параметр path теперь может являться любым URL, поддерживающим передачу списка файлов, однако в PHP 4 поддерживается только обертка file://

Примеры

Пример #1 Пример использования функции opendir()

// Открыть известный каталог и начать считывать его содержимое
if ( is_dir ( $dir )) <
if ( $dh = opendir ( $dir )) <
while (( $file = readdir ( $dh )) !== false ) <
echo «файл: $file : тип: » . filetype ( $dir . $file ) . «\n» ;
>
closedir ( $dh );
>
>
?>

Результатом выполнения данного примера будет что-то подобное:

Смотрите также

  • is_dir() — Определяет, является ли имя файла директорией
  • readdir() — Получает элемент каталога по его дескриптору
  • dir() — Возвращает экземпляр класса Directory

Установка в системах Windows

Содержание

Установка PHP в современных операционных системах Microsoft Windows и рекомендуемая конфигурация под распространённые веб-серверы.

Если вы ищете информацию о старых версиях операционных систем: Windows XP, 2003, 98 или Apache 1.x, обратитесь к разделу руководства Установка на старых версиях ОС Windows.

Официальные релизы PHP для Windows рекомендованы для использования в промышленной эксплуатации. Однако, вы также можете собрать PHP из исходных кодов. Вам потребуется окружение Visual Studio. Обратитесь к разделу » Пошаговое руководство по сборке для получения более полной информации.

Установка PHP на Azure App Services (он же Microsoft Azure, Windows Azure, или (Windows) Azure Web Apps).

User Contributed Notes 12 notes

If you make changes to your PHP.ini file, consider the following.

(I’m running IIS5 on W2K server. I don’t know about 2K3)

PHP will not «take» the changes until the webserver is restarted, and that doesn’t mean through the MMC. Usually folks just reboot. But you can also use the following commands, for a much faster «turnaround». At a command line prompt, type:

and that will stop the webserver service. Then type:

net start w3svc

and that will start the webserver service again. MUCH faster than a reboot, and you can check your changes faster as a result with the old:

in your page somewhere.

I wish I could remember where I read this tip; it isn’t anything I came up with.

You can have multiple versions of PHP running on the same Apache server. I have seen many different solutions pointing at achieving this, but most of them required installing additional instances of Apache, redirecting ports/hosts, etc., which was not satisfying for me.
Finally, I have come up with the simplest solution I’ve seen so far, limited to reconfiguring Apache’s httpd.conf.

My goal is to have PHP5 as the default scripting language for .php files in my DocumentRoot (which is in my case d:/htdocs), and PHP4 for specified DocumentRoot subdirectories.

Here it is (Apache’s httpd.conf contents):

—————————
# replace with your PHP4 directory
ScriptAlias /php4/ «c:/usr/php4/»
# replace with your PHP5 directory
ScriptAlias /php5/ «c:/usr/php5/»

AddType application/x-httpd-php .php
Action application/x-httpd-php «/php5/php-cgi.exe»

# populate this for every directory with PHP4 code

Action application/x-httpd-php «/php4/php.exe»
# directory where your PHP4 php.ini file is located at
SetEnv PHPRC «c:/usr/php4»

# remember to put this section below the above

# directory where your PHP5 php.ini file is located at
SetEnv PHPRC «c:/usr/php5»

—————————

This solution is not limited to having only two parallel versions of PHP. You can play with httpd.conf contents to have as many PHP versions configured as you want.
You can also use multiple php.ini configuration files for the same PHP version (but for different DocumentRoot subfolders), which might be useful in some cases.

Remember to put your php.ini files in directories specified in lines «SetEnv PHPRC. «, and make sure that there’s no php.ini files in other directories (such as c:\windows in Windows).

And finally, as you can see, I run PHP in CGI mode. This has its advantages and limitations. If you have to run PHP as Apache module, then. sorry — you have to use other solution (the best advice as always is: Google it!).

Hope this helps someone.

If you are installing PHP on Vista just go to David Wang’s blog. http://blogs.msdn.com/david.wang/
archive/2006/06/21/HOWTO-Install-and-Run-PHP-on-IIS7-Part-2.aspx

I made the mistake of setting a ‘wildcard application map’ for PHP on a Windows 2003 / IIS 6.0 / PHP ISAPI installation.

This resulted in «No input file specified» errors whenever I tried to load the default page in my site’s directories. I don’t know why this broke things, but it did.

If anyone has the same problem, this may be the cause.

IIS setup: 403 forbidden error.

We had installed two separate different PHP versions — PHP 5.1.4 followed by 5.2.5.

We configured 5.2.5 php5isapi.dll to be loaded as the .php file type extension.

Despite this, php version 5.1.4 was being loaded. We renamed 5.1.4’s folder and then PHP was not loading at all.

There were no visible references to 5.1.4 in the IIS configuration, but in the file \webConfig.xml, there was a reference to 5.1.4’s isapi under IISFilters.

To fix this problem, we added version 5.2.5’s php5isapi.dll to the ISAPI Filter category for the web site, in the IIS control panel.

I installed by Microsoft Installer, manually, whatever I always received de same error from IIS7.

HTTP Error 404.3 — Not Found
The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

The IIS7 interface is quite diferent and are not all together like IIS6

The 5.3 version have not any of those files: php5stdll, php5isapi.dll. etc.

The installer puts others files in handlers and I decided to use them as substitutes. Nothing done!

After that, I discovered that installer do not install these files within the sites, but in the root default site configuration of IIS7.

So, I copied the root configuration to my site and them it worked (all others procedures were done e.g. copy php.ini to windows folder)

If you get 404 page not found on Windows/IIS5, have a look at C:\SYSTEM32\INETSRV\URLSCAN

There is a .ini file there that prevents some files from being served by IIS, even if they exist, instead IIS will give a 404. The urlscan logfile (same place) should give you some insight into what parameter is preventing a page from loading, if any.

Here’s how to run dual PHP instances with PHP 5.2 and any previous PHP on Windows 2003:

1. Right-click My Computer, go to Advanced tab, and click on Environment Variables.

Add the two installations and their EXT directories to the Path variable. For example, add:
c:\php;c:\php\ext;c:\TMAS\php;c:\tmas\php\ext;

Then, add the newer PHP version’s directory as a variable called PHPRC. For example:
Variable:PHPRC
Value: C:\PHP

Click OK to close the Environment Variables window, and click OK to close System Properties.

2. In registry, under HKEY_LOCAL_MACHINE>SOFTWARE>PHP, add a REG_SZ key called iniFilePath and give it a value
of the directory where the older PHP is installed. For example:
C:\TMAS\PHP

3. In IIS, go to the Web Service Extensions. Add both versions’ ISAPI module separately to the extensions
list, and allow both.

4. In IIS, go to each website utilizing the PHP versions. Set an ISAPI filter if needed. On the Home Directory
tab, click Configuration, and add .php, .php3, .phtml, and any other extensions needed (perhaps .html?) to
be filtered through PHP, and specify the ISAPI module version needed for each website.

You can now run two versions of PHP. This is because the order of where to look for the .ini file changed
between previous PHP versions and PHP 5.2, as documented at http://us2.php.net/ini:

* SAPI module specific location (PHPIniDir directive in Apache 2, -c command line option in CGI and CLI, php_ini parameter in NSAPI, PHP_INI_PATH environment variable in THTTPD)
* The PHPRC environment variable. Before PHP 5.2.0 this was checked after the registry key mentioned below.
* HKEY_LOCAL_MACHINE\SOFTWARE\PHP\IniFilePath (Windows Registry location)
* Current working directory (for CLI)
* The web server’s directory (for SAPI modules), or directory of PHP (otherwise in Windows)
* Windows directory (C:\windows or C:\winnt) (for Windows), or —with-config-file-path compile time option
—————————————————-

PHP 5.2.9.2 Install on XP Pro IIS 5.1 — phpinfo( ) results incorrect

Testing Date: 05.15.09

Background:
For several days now I, as a newbie, have been unsure if I had installed PHP correctly, or not. No matter what I did phpinfo( ) reported «Configuratin File Path» as: “C:\WINDOWS”. I was left to wonder what was wrong.

To help resolve the phpinfo() “issue”, I conducted a series of tests using two scripts:

The first is “test-php-ini-loaded.php”; it is stored in c:\inetpub\wwwroot, and has the following code:

if ( $inipath ) <
echo ‘Loaded php.ini: ‘ . $inipath ;
> else <
echo ‘A php.ini file is not loaded’ ;
>
?>

The second script is simply calls phpinfo( ). It is named test.php, is stored in “c:\inetpub\wwroot”, and has the following code:

( ); ?>

My Dev Environment:
1. Windows XP Pro SP3
2. IIS 5.1 / MMC 3.0
3. PHP 5.2.9.2 – phpMyAdmin not yet installed
4. (plus MySQL 5.1, etc.)
5. Install location is on my local E: drive

opendir

(PHP 4, PHP 5, PHP 7, PHP 8)

opendir — Открывает дескриптор каталога

Описание

Открывает дескриптор каталога для последующего использования с функциями closedir() , readdir() и rewinddir() .

Список параметров

Путь к открываемому каталогу

Для описания параметра context обратитесь к разделу Потоки.

Возвращаемые значения

Возвращает дескриптор каталога ( resource ) в случае успеха, или false в случае возникновения ошибки

Ошибки

В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .

Может произойти, если path не является директорией, директория не может быть открыта из-за недостаточных разрешений или из-за ошибок файловой системы.

Примеры

Пример #1 Пример использования функции opendir()

// Открыть известный каталог и начать считывать его содержимое
if ( is_dir ( $dir )) <
if ( $dh = opendir ( $dir )) <
while (( $file = readdir ( $dh )) !== false ) <
echo «файл: $file : тип: » . filetype ( $dir . $file ) . «\n» ;
>
closedir ( $dh );
>
>
?>

Результатом выполнения данного примера будет что-то подобное:

Смотрите также

  • is_dir() — Определяет, является ли имя файла директорией
  • readdir() — Получает элемент каталога по его дескриптору
  • dir() — Возвращает экземпляр класса Directory

User Contributed Notes 32 notes

Sometimes the programmer needs to access folder content which has arabic name but the opendir function will return null resources id

for that we must convert the dirname charset from utf-8 to windows-1256 by the iconv function just if the preg_match function detect arabic characters and use » U » additionality to enable multibyte matching

= ( «./» ); // on this file dir

// detect if the path has arabic characters and use » u » optional to enable function to match multibyte characters

// convert input ( utf-8 ) to output ( windows-1256 )

$dir = iconv ( «utf-8» , «windows-1256» , $dir );

if( ( $dh = opendir ( $dir ) ) !== null )
<

while ( ( $file = readdir ( $dh ) ) !== false )
<

echo «filename: » . $file . » filetype : » . filetype ( $dir . $file ). «
» ;

iterated function that searches a folder or file in a directory.

= ‘../Classes’ ;
$search_parameter = «CachedObjectStorageFactory.php» ;

//if we call the function spider as spider($root);
//will show all the directory content including subdirectories

//if we call the function spider as spider(‘../Classes’, ‘Shared’);
//and will show the address of the directory

spider ( $root , $search_parameter );
closedir ();

function spider ( $dir , $fileName = «» )<

$handle = opendir ( $dir );

while( $file = readdir ( $handle ))<

if( $fileName == «» )
echo $dir . «/» . $file . «
» ;
else
if( $file == $fileName )
echo $dir . «/» . $file . «
» ;

if(! is_file ( $dir . «/» . $file ))
spider ( $dir . «/» . $file , $fileName );

An other way to recursively walk a directory and it’s content, applying a callback to each file.

Exemple: Update the last modification time of each file in a folder

// Replace \ by / and remove the final / if any
$root = ereg_replace ( «/$» , «» , ereg_replace ( «[\\]» , «/» , $sourcepath ));
// Touch all the files from the $root directory
if( false === m_walk_dir ( $root , «m_touch_file» , true )) <
echo «‘ < $root >‘ is not a valid directory\n» ;
>

// Walk a directory recursivelly, and apply a callback on each file
function m_walk_dir ( $root , $callback , $recursive = true ) <
$dh = @ opendir ( $root );
if( false === $dh ) <
return false ;
>
while( $file = readdir ( $dh )) <
if( «.» == $file || «..» == $file ) <
continue;
>
call_user_func ( $callback , » < $root >/ < $file >» );
if( false !== $recursive && is_dir ( » < $root >/ < $file >» )) <
m_walk_dir ( » < $root >/ < $file >» , $callback , $recursive );
>
>
closedir ( $dh );
return true ;
>

// if the path indicates a file, run touch() on it
function m_touch_file ( $path ) <
echo $path . «\n» ;
if( ! is_dir ( $path )) <
touch ( $path );
>
>

Here are two versions of the same function to list all files in a directory tree.

The first one is recursive (calls itself while going through subdirectories) :
function rec_listFiles ( $from = ‘.’ )
<
if(! is_dir ( $from ))
return false ;

$files = array();
if( $dh = opendir ( $from ))
<
while( false !== ( $file = readdir ( $dh )))
<
// Skip ‘.’ and ‘..’
if( $file == ‘.’ || $file == ‘..’ )
continue;
$path = $from . ‘/’ . $file ;
if( is_dir ( $path ) )
$files += rec_listFiles ( $path );
else
$files [] = $path ;
>
closedir ( $dh );
>
return $files ;
>
?>

The second one is iterative (uses less memory) :
function listFiles ( $from = ‘.’ )
<
if(! is_dir ( $from ))
return false ;

$files = array();
$dirs = array( $from );
while( NULL !== ( $dir = array_pop ( $dirs )))
<
if( $dh = opendir ( $dir ))
<
while( false !== ( $file = readdir ( $dh )))
<
if( $file == ‘.’ || $file == ‘..’ )
continue;
$path = $dir . ‘/’ . $file ;
if( is_dir ( $path ))
$dirs [] = $path ;
else
$files [] = $path ;
>
closedir ( $dh );
>
>
return $files ;
>
?>
The iterative version should be a little faster most of the time, but the big difference is in the memory usage.

Here is also a profiling function (works in php5 only) :
function profile ( $func , $trydir )
<
$mem1 = memory_get_usage ();
echo » ;
$mem2 = memory_get_peak_usage ();

printf ( » ,
( $mem2 — $mem1 )/ 1024.0 , $time );
return $list ;
>
?>

This function sorts files by name as strings, but without regard to case. It also does some handy string formatting of the file size information.

1024) $files[$fkey][‘sizetext’] = (ceil($a[‘size’]/1024*100)/100) . » K»;
else if ($a[‘size’] > 1024*1024) $files[$fkey][‘sizetext’] = (ceil($a[‘size’]/(1024*1024)*100)/100) . » Mb»;
else $files[$fkey][‘sizetext’] = $a[‘size’] . » bytes»;
$files[$fkey][‘name’] = $file;
$files[$fkey][‘type’] = filetype($fullpath);
$fileNames[$i++] = $fkey;
>
closedir($dh);
> else die («Cannot open directory: $path»);
> else die («Path is not a directory: $path»);
sort($fileNames,SORT_STRING);
$sortedFiles = array();
$i = 0;
foreach($fileNames as $f) $sortedFiles[$i++] = $files[$f];

$files = getFiles(«C:»);
foreach ($files as $file) print «$file[name]
\n»;
?>

A couple of notes on Matt’s posts on Windows Network Drives:

Since the system() command writes the output of the executed shell command straight to the output buffer, if you wish to hide the return of the mapping command (i.e. «The command completed succesfully» or an error message) from a web browser, you need to alter the command that is sent to the shell so that the output of that command is hidden.

You probably thinking «why not just use exec()?», and it’s a reasonable question, but for some reason it doesn’t always work — I guess it’s another NT user permissions issue. If you want to guarantee you app will work with no messing around on the host system, use the system() command.

In the Windows command shell, you can hide the output of a command by sending both the output (1) and error (2) messages to «nul» using pipes, in other words «>nul 2>&1» on the end of the command. The username and password order in the «net use. » command needs switching in Matt’s post.

Here (http://networkm.co.uk/static/drive.html) is a function I wrote to dynamically choose which drive letter to use, based on what is currently mapped and accessible to PHP.

// Define the parameters for the shell command
$location = «\\servername\sharename» ;
$user = «USERNAME» ;
$pass = «PASSWORD» ;
$letter = «Z» ;

// Map the drive
system ( «net use » . $letter . «: \»» . $location . «\» » . $pass . » /user:» . $user . » /persistent:no>nul 2>&1″ );

// Open the directory
$dir = opendir ( $letter . «:/an/example/path» )

Would you like to view your directories in your browser this script might come in handy.

I ran into a little snag in example 1. opendir() lists files by the last time the file was accessed. I was trying to print the files numerically in a directory.

Solution: Use scandir() instead (php5) or store the files in an array and sort it.

Hope this helps someone.

(o> Web / software developer
( ) UNIX Systems Admin

Thought I could help clarify something with accessing network shares on a Windows network (2000 in this case), running PHP 4.3.2 under Apache 2.0.44.

However you are logged into the Windows box, your Apache service must be running under an account which has access to the share. The easiest (and probably least safe) way for me was to change the user for the Apache service to the computer administrator (do this in the service properties, under the «Log On» tab). After restarting Apache, I could access mapped drives by their assigned drive letter («z:\\») or regular shares by their UNC path («\\\\shareDrive\\shareDir»).

I sometimes find this useful. Hope you will too.

//list_by_ext: returns an array containing an alphabetic list of files in the specified directory ($path) with a file extension that matches $extension

function list_by_ext ( $extension , $path ) <
$list = array(); //initialise a variable
$dir_handle = @ opendir ( $path ) or die( «Unable to open $path » ); //attempt to open path
while( $file = readdir ( $dir_handle )) < //loop through all the files in the path
if( $file == «.» || $file == «..» ) //ignore these
$filename = explode ( «.» , $file ); //seperate filename from extenstion
$cnt = count ( $filename ); $cnt —; $ext = $filename [ $cnt ]; //as above
if( strtolower ( $ext ) == strtolower ( $extension )) < //if the extension of the file matches the extension we are looking for.
array_push ( $list , $file ); //. then stick it onto the end of the list array
>
>
if( $list [ 0 ]) < //. if matches were found.
return $list ; //. return the array
> else < //otherwise.
return false ;
>
>

//example usage
if( $win32_exectuables = list_by_ext ( «exe» , «C:\WINDOWS» )) <
var_dump ( $win32_exectuables );
> else <
echo «No windows executables found :(\n» ;
>

Here is a snippet to create a site map of all html files in a folder:

// read all html file in the current directory
if ( $dh = opendir ( ‘./’ )) <
$files = array();
while (( $file = readdir ( $dh )) !== false ) <
if ( substr ( $file , strlen ( $file ) — 5 ) == ‘.html’ ) <
array_push ( $files , $file );
>
>
closedir ( $dh );
>

// Sort the files and display
sort ( $files );
echo »

    \n» ;
    foreach ( $files as $file ) <
    $title = Title ( $file );
    echo «
  • $file \» title=\» $title \»> $title \n» ;
    >
    echo «

\n» ;

// Function to get a human readable title from the filename
function Title ( $filename ) <
$title = substr ( $filename , 0 , strlen ( $filename ) — 5 );
$title = str_replace ( ‘-‘ , ‘ ‘ , $title );
$title = ucwords ( $title );
return $title ;
>
?>

I wrote a function to recursively delete files from a starting directory. I had to do this because my server doesn’t allow me to delete files that apache writes because I don’t have permissions, so. I let apache do the work.

function recursive_delete ( $dir )
<
if ( is_dir ( $dir )) <
if ( $dh = opendir ( $dir )) <
while (( $file = readdir ( $dh )) !== false ) <
if( $file != «.» && $file != «..» )
<
if( is_dir ( $dir . $file ) )
<
echo «Entering Directory: $dir$file
» ;
recursive_delete ( $dir . $file . «/» );
echo «Removing Directory: $dir$file

I was trying to access network drives using this opendir function. I read so many posts saying that it was almost impossible to access a network drive and finally, I found the answer; there are 2 steps to be followed to access a network drive with PHP either on the same machine or another machine.

But first of all, here’s the error I was getting:
Warning: opendir(\\server\folder1\sub_folder) [function.opendir]: failed to open dir: No error in C:\wamp\www\PMOT\v0.1\REPORT_MENU\index.php on line 17

Firstly, one must make sure that the folder \\server\folder1\sub_folder can be accessed by a user, let’s say USER_TEST with a password PASS_TEST. By setting properties to this folder, one can add this given user with the correct password (USER_TEST with PASS_TEST).

Secondly, the APACHE service must be set-up to take this user into account. If no user is specified, APACHE uses an anonymous user and this is where the problem/error message is coming from. One must go in control panel->administrative tools->services. One will see the list of services and must look for APACHE with Apache/2.X.X in the description. (For Wampserver, it will be called wampapache, and so on!) Right click on that and pop up the properties screen. In the tab LOG ON, there are 2 options: local system account and «this account» which will be a user specified account. This is where one must specify the USER_TEST and PASS_TEST.

Following these steps worked perfectly for me but if either the folder privileges or apache log on user is disabled, then I get the initial aforementioned error message.

Читайте также:  Техническое задание для windows
Оцените статью