user1985014
user1985014

Reputation: 91

Read file on a network drive

I'm running Xampp on a Windows Server ; Apache is running as a service with a local account. On this server, a network share is mounted as X: with specific credentials.

I want to access files located on X: and run the following code

<?php
echo shell_exec("whoami");
fopen('X:\\text.txt',"r");
?>

and get

theservername\thelocaluser
Warning: fopen(X:\text.txt) [function.fopen]: failed to open stream: No such file or directory

I tried to run Apache, not as a service but directly by launching httpd.exe ... and the code worked.

I can't see what causes the difference between the service and the application and how to make it works.

Upvotes: 9

Views: 50708

Answers (3)

dhrty
dhrty

Reputation: 31

If it helps for the future, what i did was this:

  1. Create a local account with the same username and password as the account which you access to the network drive.
  2. Go to Windows Services > Apache2 > Properties > Login > Log in as this account ... and specify the username and password that you created.

About the syntax, the one that worked for me was:

$fileName = '//192.168.1.10/Folder/file.txt';

I'm using php 8.

Upvotes: 3

Lawrence Cherone
Lawrence Cherone

Reputation: 46610

For network shares you should use UNC names: "//server/share/dir/file.ext"

If you use the IP or hostname it should work fine:

$isFolder = is_dir("\\\\NAS\\Main Disk");
var_dump($isFolder); //TRUE

$isFolder = is_dir("//NAS/Main Disk");
var_dump($isFolder); //TRUE

$isFolder = is_dir("N:/Main Disk");
var_dump($isFolder); //FALSE

Upvotes: 7

Rudi Visser
Rudi Visser

Reputation: 21979

You're not able to do this using a drive letter, as network mapped drives are for a single user only and so can't be used by services (even if you were to mount it for that user).

What you can do instead is use the UNC path directly, for example:

fopen('\\\\server\\share\\text.txt', 'r');

Note, however, that there are a few issues with PHP's filesystem access for UNC paths. One example is a bug I filed for imagettftext, but there are also issues with file_exists and is_writeable. I haven't reported the latter because as you can see from my long-outstanding bug with imagettftext, what's the point.

Upvotes: 16

Related Questions