Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Connect to a MS SQL Server with Dynamic Port Allocation

Tags:

php

sql-server

I'm trying to browse a customer's Microsoft SQL server database with PHP but port 1433 is closed. Digging around I found out MSSQL can run in Dynamic Port Allocation mode, that means it will choose a random listen port at first execution, and will likely remain the same accross startup. I know I can find out the current port, but since likely is not always and I'd like to avoid searching for it again, is there any way to remotely discover the port to connect to?

From what I could understand by my searches this job is usually accomplished by SQLBrowser(.exe ?), but how to do this on Linux?

Update on the solution

While @Chris' answer was correct I was missing a simple but essential bit: on every change of odbc.ini you need to run:

odbcinst -i -s -f /etc/odbc.ini

to update system's DSN. After that I could connect using

isql -v DSN_NAME username password

Troubleshooting

To check server instance:

tsql -H HOSTNAME_OR_IP -L

this will print server information, including instance names and port to which you should be able to connect using standard telnet or mssql client.

like image 698
Maxxer Avatar asked Apr 02 '14 14:04

Maxxer


1 Answers

Given that your answer was correct, I had to do minor changes to make it work. I decided to write them here. Steps are basically the same. On Ubuntu/Debian:

apt-get install php5-sybase unixodbc tdsodbc

Edit /etc/odbcinst.ini and add driver details

[TDS]
Description = FreeTDS Driver
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so

Edit /etc/odbc.ini and enter connection details

[SQLSRV01]
Description = SQL Server test
Driver = TDS
Trace = No
Server = SERVER_IP\INSTANCE_NAME
TDS_Version = 9.0
#Database = DataBaseName
#ReadOnly = Yes

The last two parameters are optional. Driver must match what we wrote in odbcinst.ini. The Server directive must be in that syntax (of course SERVER_IP can be an hostname too).

According to UnixODBC the next step should not be necessary, but this is what made my installation work. Run the following command (every time odbc.ini is changed)

odbcinst -i -s -f /etc/odbc.ini

After this you should be able to connect using:

isql -v SQLSRV01 nome_utente password

Or via PHP:

$db = new PDO("dblib:host=SQLSRV01;dbname=DBNAME","USERNAME","PASSWORD");
like image 195
Maxxer Avatar answered Sep 27 '22 23:09

Maxxer