Reading file list from a mapped Windows network drive

Posted by Stanislav Furman  on March 25, 2013

Last week I ran into a situation when I had to read directory file list from a mapped Windows network drive. At your very first look it may seem pretty simple. It is! However, there is a little trick - Windows may require your network/domain credentials, and then standard PHP functions such as opendir() won't be able to access the directory. Fortunately, the solution is pretty simple:


<?php
$path = '\\networkdrive\somepath\your_directory';

$user = "username";
$pass = "password";
$drive_letter = "Q";

system("net use ".$drive_letter.": \"".$path."\" ".$pass." /user:".$user." /persistent:no>nul 2>&1");
$location = $drive_letter.":/somepath/your_directory";

if ($handle = opendir($location)) {
    while (false !== ($entry = readdir($handle))) {
	echo "$entry";
    } 
    closedir($handle);
}
?>

Update: If you run the script on Windows localhost, you will need to run your localhost Apache as administrator. If this doesn't work, try to restart Apache service from Windows Administrator tools. 

Update 2: File search and wildcards in PHP.


Comments

david says:
March 7, 2014 at 09:05 pm
Please correct this code... (1) $letter is not defined (2) $handle is not defined
Flag as SPAM  |  Permalink
Stan says:
March 29, 2014 at 06:09 pm
Thanks, David!
I've updated the code.
Flag as SPAM  |  Permalink
Steve says:
November 2, 2015 at 04:58 pm
Worked perfectly! Been searching for an answer for this, thanks a ton!
Flag as SPAM  |  Permalink
Abdelrahman says:
February 9, 2016 at 01:04 pm
Kindly give an example
what you mean by somepath , your_directory and drive_letter
Flag as SPAM  |  Permalink
dhinakar says:
September 17, 2016 at 07:12 am
How to connect other network drive? give me a example
Flag as SPAM  |  Permalink

Leave your comment

Fields with * are required.

* When you submit a comment, you agree with Terms and Conditions of Use.