Skip to content

Instantly share code, notes, and snippets.

@AWS-ServerLink
Last active November 3, 2023 10:05
Show Gist options
  • Save AWS-ServerLink/a3fbba66a526456654f8592023b4c002 to your computer and use it in GitHub Desktop.
Save AWS-ServerLink/a3fbba66a526456654f8592023b4c002 to your computer and use it in GitHub Desktop.
How to get Microsoft PHP drivers working with Amazon Linux 2 (pdo_sqlsrv, sqlsrv_connect)

Prerequisites

  • Amazon Linux 2 EC2 instance
  • Firewall port 80 open
  • Base Linux sysadmin ability

Steps

  • SSH into your Amazon Linux 2 instance
  • Make a test sqlsrv_connect page in your document root (eg /var/www/html/) see below
  • Follow the commands below
  • Run "php -m" and you should see pdo_sqlsrv and sqlsrv in the list of PHP modules
  • Test all is working by running the test sqlsrv_connect page (eg http://InstanceIP/index.php)

Commands

sudo su
sudo yum-config-manager --add-repo https://packages.microsoft.com/config/rhel/7/prod.repo
exit
sudo yum update
sudo ACCEPT_EULA=Y yum install -y php msodbcsql mssql-tools unixODBC-devel php-devel php-pear php-pdo php-xml re2c gcc-c++ gcc
amazon-linux-extras install -y lamp-mariadb10.2-php7.2 php7.2
sudo pecl install sqlsrv
sudo pecl install pdo_sqlsrv
sudo sudo amazon-linux-extras install -y lamp-mariadb10.2-php7.2 php7.2
echo "extension=sqlsrv" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`
echo "extension=pdo_sqlsrv" >> /etc/php.d/30-pdo_sqlsrv.ini
exit
sudo setsebool -P httpd_can_network_connect_db 1
sudo systemctl restart httpd && sudo apachectl restart

sqlsrv_connect test page

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

$serverName = "[YOUR_DB_ADDRESS]";
$connectionOptions = array(
    "Database" => "[DB_NAME]",
    "Uid" => "[USER]",
    "PWD" => "[PASSWORD]"
);

$conn = sqlsrv_connect($serverName, $connectionOptions);
if($conn === false )
{ print "Working"; } else { print "Error"; }

?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment