Php read file contents of network share file
Asked Answered
H

2

6

I'm looking for a way to read the file contents of a file located on a network share. I can use the IP Address of the share host and the share folder to get to the location but I don't know the correct command and syntax to do that file_get_contents? fopen?

$text = fopen('//128.251.xxx.xxx/Common/sample.txt', 'r');

or something like that?

UPDATE* I also cannot access the file through a browser window although I know the file is located in that exact directory...

Hermaphrodite answered 21/2, 2011 at 19:51 Comment(0)
W
8

The best way (depending on your needs) is to simply mount it on your local machine, and then read from the mount. That lets all the network interaction be abstracted away.

So, in Linux:

mount -t cifs //192.168.XXX.XXX/share /path/to/mount -o user=username,password=password

Then, in php, just access it from the mount point:

$data = file_get_contents('/path/to/mount/path/to/file.txt');
Waggoner answered 22/2, 2011 at 14:14 Comment(0)
R
4

According to PHP Filesystem manual UNC/SMB files should be accessible. Try the following:

\\server\share\file.txt

It may be one of those cases where the // may be mistook as a reference to the root directory. And given this is an SMB path, I would use the traditional backslashes.

Ramos answered 21/2, 2011 at 20:13 Comment(10)
if you use "\", do you not have to escape it? i.e. "\\".Paramedical
@Kenny: Yes, in a string this needs to be escaped. I was just elaborating with the path to use and that PHP can handle it.Ramos
it says I can use fopen and others to add parameters but the syntax is $text = \\smbserver\share\path\to\winfile.ext ... which seems odd that the syntax would be that.Hermaphrodite
@sadmicrowave: I believe you're looking for fopen("\\\\server\\share\\file.txt","r")Ramos
@BradChristie - PHP Warning: fopen(\\128.251.xxx.xxx\Common\DdfStamps.txt): failed to open stream: No such file or directory in /home/coreyf/Documents/php/test.php on line 7Hermaphrodite
@sadmicrowave: What version of PHP are you running? Everything I see on PHP's website says this should work.Ramos
@sadmicrowave: Comes down to permissions then. Is this Apache/IIS hosted? You need to make sure the web host offering up the page has access to the resource (might be that the web host has computer-level permissions which don't pass credentials on the shared resource itself.Ramos
@BradChristie - are you telling me that php is limited to only accessing files on webservers? I cannot read a file's contents if given the path to a file server? (which is my case here)Hermaphrodite
@sadmicrowave: No, I'm saying PHP canm given the permission to. It just has to be allowed access to the remote resource.Ramos
Dont use backslashes, this is one of those cases where you need forward slashes: open("//server/share/file.txt")Mcconaghy

© 2022 - 2024 — McMap. All rights reserved.