PHP to MySQL using SSL - php

I have a remote MySQL Server that requires me to use SSL for connections. I can connect to it using my terminal. But when I try to connect to it using PHP, I get the following error:
SSL3_GET_RECORD:wrong version number
It seems like the OPENSSL Handshake fails and the reason could be that my PHP is trying to connect to it using SSL3. The MySQL Server supports only TLSv1.2. Is there a way to force PHP to connect using TLSv1.2 ?
Here is my code used to connect:
<?php
ini_set ('error_reporting', E_ALL);
ini_set ('display_errors', '1');
error_reporting (E_ALL|E_STRICT);
$db = mysqli_init();
mysqli_options ($db, MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, true);
$db->ssl_set(NULL, NULL, '/path/to/ca-cert.pem' , NULL, NULL);
$link = mysqli_real_connect ($db, 'hostname', 'user', 'password', 'dbname', 3306, NULL, MYSQLI_CLIENT_SSL);
if (!$link)
{
die ('Connect error (' . mysqli_connect_errno() . '): ' . mysqli_connect_error() . "\n");
} else {
$res = $db->query('SHOW TABLES;');
print_r ($res);
$db->close();
}
?>
Things I have tried and possible problems:
Seems like openssl version mismatch. I can connect using my terminal and not PHP, so I checked my openssl version in the terminal with the one I get using phpinfo(), they were the same
PHP is possibly using SSL3 to connect, and the server only supports TLSv1.2, I wasn't able to find a way to force PHP connections to MySQL using TLSv1.2
I tried to observe the handshake using tcpdump/Wireshark, but I don't think the process even starts since there is a version mismatch.
I confirmed using "openssl s_client -debug" that the server doesn't support SSL3 which makes me think this is an issue on my computer, but not sure.
The reason I say my client might be using SSL3 is because of SSL3_GET_RECORD, I don't know for sure if I'm right in that too.
So, in short, Help!
Environment:
PHP 7.0.18
MySQL Server Enterprise version 5.7.18
OpenSSL 1.0.2g
OS: Windows 7, Ubuntu 16.04. Tried on both

The problem was the driver that PHP used to connect to MySQL. By default, it is mysqlnd. And I don't think it was being able to connect using a SHA256 or better cipher to my MySQL Server, which is an enterprise version.
The other option for the driver is a libmysql library which Oracle does provide as part of the MySQL Enterprise Server (.deb files). I started with a clean OS(Ubuntu), and compiled PHP with the libmysql provided by Oracle, and then I was able to establish the connection successfully!
More info here

Related

SQLSTATE[01002] Adaptive Server connection failed (severity 9) error on Ubuntu Linux VPS

I am trying to connect to an Azure Microsoft SQL Server database on my php scripts. I cannot figure out why it isn't working. When I run my db_connection.php script, I get this error:
SQLSTATE[01002] Adaptive Server connection failed (severity 9)
When I run the tsql command, with the connection details for my azure ms sql database, the connection seems to work (I read the "1>" means the connection worked):
locale is "C"
locale charset is "ANSI_X3.4-1968"
using default charset "UTF-8"
Default database being set to iBalekaDB
1>
Inside my freetds.conf file, I have this configuration set up:
# server specific section
[global]
# TDS protocol version
tds version = 8.0
text size = 20971520
client charset = UTF-8
dump file = /tmp/freetds.log
debug flags = 0xffff
# Command and connection timeouts
; timeout = 10
[iBalekaServer]
host = xxxxxxxx.xxxxxxx.windows.net
port = 1433
tds version = 8.0
client charset = UTF-8
My db_connection.php file looks like this:
try {
$dataSource = "dblib:host=iBalekaServer;dbname=iBalekaDB;";
$username = "xxxxxxxxxxxx";
$password = "xxxxxxxxxxxx";
$connectionObject = new PDO($dataSource, $username, $password);
$connectionObject->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($connectionObject) {
echo "<h2>Connection Successful</h2>";
} else {
echo "Connection Error";
}
} catch (PDOException $e) {
echo $e->getMessage();
}
I ran tsql -C on the VPS and got this:
Compile-time settings (established with the "configure" script)
Version: freetds v0.91
freetds.conf directory: /etc/freetds
MS db-lib source compatibility: no
Sybase binary compatibility: yes
Thread safety: yes
iconv library: yes
TDS version: 4.2
iODBC: no
unixodbc: yes
SSPI "trusted" logins: no
Kerberos: yes
I checked to see if I had pdo_dblib installed, and it was present when I ran phpinfo() on my Linux VPS Server.
What could be the issue here?
EDIT: using mssql_connect works. I really wanted to use PDO
On my test, I changed the $username to the format of UID (e.g. <username>#<db_server_name>), and it fixed your issue of SQLSTATE[01002] Adaptive Server connection failed (severity 9).
BTW, you can grab the UID from the connectionstring from Azure portal.
Additionally, if you get the issue of General SQL Server error: Check messages from the SQL Server (severity 16), you can refer to the answer of PDO DBLib not working.
Any update, please feel free to let me know.

MSSQL VIA FreeTDS, ODBC, and Cpanel Unknown host machine name (severity 2)

I have installed FreeTDS 0.91, ODBC, on a Cpanel server running Centos 6.5x64. Everything appears to be running fine and I can connect to the remote MSSQL 2012 server using:
/usr/local/freetds/bin/tsql -S sqlserver -U test -P mypassword
and succesfully execute queries in the database.
I can also connect through:
isql -v sqlserverdatasource test mypasswordhere
But for some reason /usr/local/freetds/bin/tsql -LH server.ip.here
returns no information or errors which doesn't make much sense when it is proven I can connect with the other methods above.
So now when running a test script from a cpanel account on the machine I get:
Unknown host machine name (severity 2)
Here is the test script:
//Database connection function.
function getConnection() {
try {
//$dbconnect = new PDO("sqlserver:Server=server.ip.here,1433;Database=dbname", "user", "password");
$dbconnect = new PDO("dblib:host=server.ip.here,1433;dbname=dbname", 'user', 'password');
} catch (PDOException $e) {
echo "CONNECTION ERROR.<br>Error message:<br><br>" . $e->getMessage();
die();
}
if (!$dbconnect) {
die('Cant connect to database. Please try again later!');
}
else{
echo "i'm in!";
return $dbconnect;
}
}
The first commented line is the old one using sqlserv which I found did not work at all from what i can tell because of the x64 OS. I have also tried with "" around user and pass as well as no marks at all.
php -m does show PDO and pdo-dblib.
Any ideas where I can look next?
Update: This was fixed. I missed in freetds.conf:
[global]
# TDS protocol version
tds version = 8.0
It was originally set to 4.5 instead of 8.
The fix for me was with three steps:
First, I edited /etc/freetds/freetds.conf and changed the tds version like this:
tds version = 8.0
The second step was not entering port number. The port was already 1433, and not specifying it fixed the exact same issue on my case.
Lastly, to connect properly, I had to restart networking as #user1054844 mentioned as this:
/etc/init.d/networking restart
After all these steps, I was able to connect and work with the SQL Server database.
You actually did not need ODBC at all since your connect script is using pdo_dblib not odbc. You can just install FreeTDS than enable pdo_dblib via the compile time flag in rawopts and rebuild via EasyApache. Of course cPanel specifics for this are a bit different.
I just did this for a friend and decided to document it since it is hard to find accurate clear information for FreeTds and pdo_dblib on cPanel.
Guide is here: FreeTDS And pDO_dblib On cPanel

mysql communicate with mssql on different server via php

I have mysql on a linux server which I own having CentOS installed in it. I want to fetch data from another windows server having mssql database.
I need to create a php script that can get the values from mssql server and insert it into mysql server.
I have tried installing FreeTDS also PDO but still I am unable to connect (not sure if I have installed it properly). The error messages I get are Could not Connect to the server and drivers not found.
How can I check if I have installed freetds and PDO drivers correctly.
Basic Diagram of what I am trying to do:
Server A (Mumbai) {Linux Cent OS, FreeTDS and PDO installed} ---------> Server B (Delhi) {Windows, MSSql}
I want to get data from Server B to Server A.
locale is "en_US.UTF-8"
locale charset is "UTF-8"
using default charset "UTF-8"
62Error 20009 (severity 9):
Unable to connect: Adaptive Server is unavailable or does not exist
OS error 110, "Connection timed out"
There was a problem connecting to the server
root#server [~]# tsql -C
Compile-time settings (established with the "configure" script)
Version: freetds v0.91
freetds.conf directory: /usr/local/etc
MS db-lib source compatibility: no
Sybase binary compatibility: no
Thread safety: yes
iconv library: yes
TDS version: 5.0
iODBC: no
unixodbc: yes
SSPI "trusted" logins: no
Kerberos: no
How can I update TDS version form 5 to 7
Please guide.
Use ADODB Connection
$conn = new COM ("ADODB.Connection", NULL, CP_UTF8) or die("Cannot start ADO");
$connStr = "PROVIDER=SQLOLEDB;SERVER=myServer;UID=myUser;PWD=myPass;DATABASE=myDB";
$conn->open($connStr); //Open the connection to the database
$SQL="SELECT id, .........................";
$res=$conn->execute($SQL);
while (!$res->EOF) //carry on looping through while there are records
{
$id=$res->Fields('id')->value;
}
http://php.net/manual/en/class.com.php
Now go to Example #2 COM example (2)
Well, you can use the mssql select querys, set a variable in php with the result from the mssql query, and then do a mysql insert query to insert it into your database
$link = mssql_connect($server, 'sa', 'phpfi');
mssql_select_db('php', $link)
$query = mssql_query('SELECT [id] FROM [php].[dbo].[userlist]');
while ($row = mssql_fetch_assoc($query)) {
$row['id']
$con=mysqli_connect("127.0.0.1","root","pass","db");
mysqli_query($con,"INSERT INTO tablname VALUES('$id')");
}
Give this a try.
Of course you have to customize it to fit your needs.
Configure FreeTDS
This is a perfect tutorial for configuring FreeTDS. Every thing from basic..superb tutorial.
Thanks to Hugo Brown.

Can not connect to SQL SERVER Using Latest Drivers for PHP

I have been trying to figure out which dll and how to use it to connect to sql server.
It was much easier using the old php_mssql.
I am using Xampp on WinXP Pro SP3. I have been unable to figure out how to connect, i have search the manual, and none of the command's work.
I get PDO Error Driver Not Found
extension-php_pdo_sqlsrv_54_ts.dll
extension=php_sqlsrv_54_ts.dll
I realized that I must use the SQLSERV 2.0 Drivers. But which dll is the correct one? And what syntax must I use to connect and run queries?
Thank you.
One way of doing this is using FreeTDS for Windows
I am assuming you have PHP >5.3
Download this http://download.moodle.org/download.php/dblib/php53/DBLIB_TS.zip
Add this line to your php.ini extension=php_dblib.dll
You will also need to make a file called freetds.conf in the root directory of your PHP installation.
It should look something like this:
[global]
host = xxx.xxx.xxx.xxx (host name or ip of the MSSQL server)
port = 1433
client charset = UTF-8
tds version = 8.0
text size = 20971520
Restart Apache and try running this script:
<?php
$link = mssql_connect('localhost', 'db_user', 'db_password');
if(!$link) {
echo'Could not connect';
die('Could not connect: ' . mssql_error());
}
echo'Successful connection';
mssql_close($link);
?>
hit me up on fb if this does not work ;)

No error messages returned when mysql_connect does not work for PHP on IIS

I am new to PHP and MySQL and have recently installed both PHP v5.3.10 and MySQL v 5.5.21 on a Windows Server 2003 server already running IIS v6.
PHP runs and I have created a database on MySQL from the MySQL 5.5 Command Line Client.
However, when I try to access the database from PHP with the following commands:
echo "Open database";
$link = mysql_connect($host, $username, $password);
echo " link: $link";
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_name, $link)or die("cannot select DB");
echo " database open";
I get the following returned to the web page:
Open database
No error messages are produced and nothing after the mysql_connect command is returned from
the PHP to the screen.
Also tried line below which also did not return any error messages:
mysql_connect($host, $username, $password) or die('Cannot connect:' . mysql_error());
Anybody have any ideas why I can't make a connection and can't get an error message back from mysql_connect command?
I have checked MySQL and I have tried defining the host as %, localhost, the local host IP and the IP:port number (from the port number 3306 listed in the my.ini) to no effect.
I only have one username of 'root' created in mySQL with a single password (which I used when I opened MySQL to create the database)
The 'php.ini' I have placed in both the 'C:\Program Files\PHP' and 'C:\WINDOWS'.
This file contains 'extension_dir = "C:\Program Files\PHP\ext"' to specify the extension directory and includes the following at the end of the file:
[PHP_PDO_MYSQL]
extension=php_pdo_mysql.dll
[PHP_MYSQL]
extension=php_mysql.dll
[PHP_MYSQLI]
extension=php_mysqli.dll
Also I tried running phpinfo() and it returned the following table for mysqlnd:
mysqlnd enabled
Version mysqlnd 5.0.8-dev - 20102224 - $Revision: 321634 $
Compression supported
SSL supported
Command buffer size 4096
Read buffer size 32768
Read timeout 31536000
Collecting statistics Yes
Collecting memory statistics No
Tracing n/a
So Is I assume the php should be able to connect.
Try this:
ini_set('display_errors',1);
error_reporting(E_ALL);
To mirror #Jrod:
is error_reporting on?
have you checked the error_log for the instance?
It sounds like something's failing and your error reporting isn't set high enough to show it. You might try addin this to the top of the script:
error_reporting(E_ALL);

Categories