Search code examples
phpapachenetwork-programmingexecdrive

PHP's exec() can't access network drive


In PHP, I list some file by calling exec("dir ..."). However, this strangely works only on local drives. On network drives it has non-zero result status code and no results are returned.

I run Apache on Windows XP Professional.

Is there any trick to fix this? Or to view an error message?

EDIT: apache is running under the same user as I am and I can do it from the command line


Solution

  • I was going to say "you can't do it from the command line either", and I'm sure that used to be true, but I have just tried on WinXP Pro SP3 and it is working, just to spite me.

    I had to get PHP to talk to a network drive some time ago (when I was decidedly greener in the world of PHP), and I had a nightmare getting it to work, however eventually I managed to get it to work by doing the following:

    • In the "Services" MMC snap-in, change the user account that Apache runs under to a local user. It will probably be set to SYSTEM at the moment and (AFAIK) that account does not have access to network drives. You will need to restart the service after you do this.
    • Add the following line before you try and access it: system('net use Z: "\\servername\sharename" PASSWORD /user:USERNAME /persistent:no');, where you change the drive letter, UNC path, username etc to match your requirements. Do this even if the drive is already mapped. I seem to remember that I had to use system() instead of exec() or shell_exec() or it didn't work - as a result, you need to output-buffer to stop the output being passed to STDOUT.

    I have no idea why this worked, but it did. Note, though, that I was trying to use the drive with native PHP functions like opendir() and fopen(), rather than trying to exec() an external program against it.

    If you want to view the error messages from your call to dir, append 2>&1 to the end of the command. This will redirect STDERR to STDOUT, so you should get the error messages in the result of exec().

    So your line would look like:

    exec("dir Z:\\some\\path 2>&1")