Accessing to Windows files from a Linux Server in PHP without mounting a Samba partition is really easy with libsmbclient-php, a PHP extension that uses Samba’s libsmbclient library to provide Samba related functions to PHP.
After installing the library, you will be able to manipulate your files and folders just like you do in Linux by using the smb:// prefix.
smbclient Installation
Make sure you have samba, samba-client installed on your server, then install smbclient.
PECL Installation
1 |
pecl install smbclient |
Package Installation
See https://apps.fedoraproject.org/packages/php-smbclient for this method, this requires Remi repository on CentOS.
1 |
yum install php-smbclient.x86_64 |
From sources
Take it from GitHub then compile it.
The next step requires you to grab your Windows NTLM Authentication and make sure the user you are using with PHP has the right to access the files.
libsmbclient-php example script
This quick example PHP script shows how to use libsmbclient-php.
It opens a connection to a Windows server via a username & password, read a file, then delete it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
$configuration = array('username' => 'Windows User', 'password' => 'Windows Password'); # Windows file content $binary = ''; # Create new SMBClient state: $state = smbclient_state_new(); # Initialize the SMBClient State with Workgroup (null here), Username & Password if (smbclient_state_init($state, null, $configuration['username'], $configuration['password'])) { # Opening file if ($file = smbclient_open($state, rawurlencode('smb:' . preg_replace('/\\\/', '/', $filename)), 'r')) { # Reading file while (true) { $data = smbclient_read($state, $file, 100000); if (($data === false) || (strlen($data) === 0)) { break; } $binary .= $data; } # Closing connection smbclient_close($state, $file); # Deleting file smbclient_unlink($state, rawurlencode('smb:' . preg_replace('/\\\/', '/', $filename)) } else { # Unable to open the file } } else { # Unable to login } # Freeing state smbclient_state_free($state); |
A simpler version can be made because most standard PHP functions will work with ‘smb’ URIs. (Like file_get_contents, file_put_contents, fopen, mkdir, opendir, unlink, …)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$configuration = array('username' => 'Windows User', 'password' => 'Windows Password'); # Windows file content $binary = ''; # Computing path $path = rawurlencode('smb://' . $configuration['username'] . ':' . $configuration['password'] . '@server' . $filename); # Opening & deleting file if ($binary = file_get_contents($path)) !== false) { unlink($path); } else { # Error } |