I'm fairly new to using PHP to connect to a SQL Database and I am having an issue where I receive this error message, when trying to connect to a database via sqlsrv_connect():
[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
I've followed the instructions found here and have placed this extension; php_sqlsrv_53_nts.dll, into the php.ini file. Phpinfo() shows sqlsrv as enabled on the web server but I still receive the same error when trying to connect to the data source.
Below is the code I am using:
$db_server = 'tcp:192.168.0.1';
$db_credentials = array('UID' => 'Domain\Username', //SQL Server UID
'PWD' => 'Password', //SQL PW
'Database' => 'ThisDatabase', //Name of the database
'CharacterSet' => 'UTF-8',
'ConnectionPooling' => 'False',
'LoginTimeout' => 60); //Number of Seconds before fail
$db_connect = sqlsrv_connect($db_server, $db_credentials);
//Check the connection to the SQL Database to see if it's valid or else display errors.
if ($db_connect === false) {
die(print_r(sqlsrv_errors(), true));
} else {
echo "Success: Connected to database.";
};
I'm completely stumped, so any help will be useful!
As suggested by #Terminus, installing either the SQL Server driver or SQL Native Client driver on the web server resolves the problem.
Related
GOAL: To use a PHP webjob to connect and alter SQL database table in Azure.
I'm trying to upload a .zip file containing a .php and a .json file to the webjobs settings inside of an app service I have running on Azure.
I believe there's something wrong with the way I'm coding the PDO-SQL connection inside of the PHP file, when I upload the webjob as a .zip into webjobs, the Status is always "Pending Restart".
Here's what I have in my .php file:
<?php
$conn = new PDO ( "sqlsrv:server = mydb.database.windows.net,1433; Database = myappservices");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
catch ( PDOException $e ) {
print( "Error connecting to SQL Server." );
}
$connectionInfo = array("Database" => "myappservices");
$serverName = "mydb.database.windows.net,1433";
$conn = sqlsrv_connect($serverName, $connectionInfo);
if ($conn) {
$stf = $conn->prepare("INSERT INTO MyTable
VALUES ('boom', 1, 2);");
$stf->execute();
}
?>
Then my .json file is just a scheduler:
{
"schedule": "0 */5 * * * *"
}
These are the only two files in my .zip file I'm uploading.
To explain the PHP code, I'm trying to connect via windows authentication (no need for user/pass). Maybe I'm doing this wrong too.
Anyone have any ways to do this? I would really appreciate giving a step by step or suggestions as to how to change my code to get this webjob to actually run.
Consider this job.php:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
try {
// DON'T HARDCODE CREDENTIALS, pull from Application Settings.
// In Azure App Service, Application Settings are exposed as
// environment variables.
//
// i.e. $db_user = getenv("DB_USER");
//
$conn = new PDO ("sqlsrv:server = poqfsXXXX.database.windows.net,1433;
Database = MobileApp_db",
"Username", "P#ssw0rd");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
print("Error connecting to SQL Server: " + $e);
}
$stmt = $conn->prepare("select * from todoitems");
$stmt->execute();
while ($row = $stmt->fetch()) {
print_r($row);
}
unset($conn);
unset($stmt);
?>
Expected output:
(You can test in Kudu: https://{sitename}.scm.azurewebsites.net/DebugConsole)
d:\home\site\tests> "d:\program files (x86)\php\v5.6\php.exe" job.php
Array
(
[Id] => d4657cff-09a2-4a8a-b1d2-462c2c42a9f0
[0] => d4657cff-09a2-4a8a-b1d2-462c2c42a9f0
[Text] => From Azure SQL
[1] => From Azure SQL
[Complete] => 0
[2] => 0
[Version] => 0000000000001825
[3] => 0000000000001825
[CreatedAt] => 2016-06-17 10:11:17.1167267 +00:00
[4] => 2016-06-17 10:11:17.1167267 +00:00
[UpdatedAt] => 2016-06-17 10:11:17.1167267 +00:00
[5] => 2016-06-17 10:11:17.1167267 +00:00
[Deleted] => 0
[6] => 0
)
Array
(
...
)
...
To explain the PHP code, I'm trying to connect via windows authentication (no need for user/pass). Maybe I'm doing this wrong too.
While Azure SQL does support Windows Authentication, i'm not exactly sure what you mean by "no need for user/pass". Windows Authentication means "take the credentials of whomever this process is running as and attempt authentication against the SQL server". Since you're running your Webjob as a random user provided by the sandbox, Windows Authentication doesn't make much sense.
From Kudu's Process Explorer:
Here's one valid scenario for Windows Authentication with Azure SQL:
You have an on-prem hosted application that uses Active Directory to authenticate to your on-prem SQL Server. You have a requirement to move to Azure SQL. You do not have the option to change the authentication method for SQL. So you dirsync your directory to Azure AD and use Windows Authentication to connect to Azure SQL.
More on Windows Authentication in Azure SQL:
https://azure.microsoft.com/en-us/documentation/articles/sql-database-aad-authentication/
I'm browsing the web for two days in 3 languages, but unfortunately couldn't find an answer (checked the questions here of course, but the one identical was unanswered).
There's a virtual server with apache 2.4,php 5.6.7,oracle instant client 12_1 (32 bit). After a few restarts and ini configuration I managed to use PDO odbc and plain oci_connect(). BUT when I try PDO OCI I get this error message:
Error!: SQLSTATE[HY000]: pdo_oci_handle_factory: ORA-12560:
TNS:protocol adapter error (ext\pdo_oci\oci_driver.c:635)
The TNS name I set was successfully used in SQL developer to connect.
I'm fairly new to this environment so please ask for the information you might need.
Try something like this.
$conn = new Pdo("oci:dbname=(DESCRIPTION = (ADDRESS_LIST = (
ADDRESS = (PROTOCOL = TCP)
(HOST = {$params['host']} )
(PORT = {$params['port']} )
))
(CONNECT_DATA = (SID = {$params['servicename']})
)); charset=AL32UTF8",
$params['user'],
$params['password']
);
Nodejs trying to connect to a database and pulls me hostinger this error before i use http://www.freemysqlhosting.net/ was similarly placing the host, user, pass and name of the database and did not erro I think that is the port but idk .. I'm using: app.listen (process.env.PORT || 3000)
So I'm doing:
var connection = mysql.createConnection ({
host: 'mysql.hostinger.es',
user: 'XXXXX',
password: 'XX',
database: 'XXX',
});
Error I get:
It tells you that it couldn't resolve mysql.hostinger.es
Check it's the good hostname or try to set directly the IP address.
I have recently created a script which should be passed an IP address of the users FM DB Server location, then the script will connect to that server with the given username, password, IP Address and DB Name.
However, no matter what I pass as the IP, it never throws an error.
Is there some form of error handling within the FileMaker PHP API for connection errors?
Thanks in advance!
All the FileMaker API calls return an result object in case of error. You should try this:
Here is an example:
$fm = new FileMaker();
// Set 'hostspec' property using setProperty()
$fm->setProperty('database', $fmConfig['db']);
$fm->setProperty('hostspec', $fmConfig['host']);
$fm->setProperty('username', $fmConfig['user']);
$fm->setProperty('password', $fmConfig['pass']);
$dt = date('m/d/Y H:i:s', $myDate);
$freq = $fm->newFindCommand("myTestLayout_1.0") ;
$freq->addFindCriterion("ModificationTimeStamp", ">".$dt);
$result = $freq->execute();
if (FileMaker::isError($result)) {
$ErrMsg = 'Error code: '.$result->getCode().' Message: '.$result->getMessage();
throw new Exception ($ErrMsg);
}
$foundRecords = $result->getRecords();
echo count($foundRecords)." records";
The server that you're making the calls from needs to have curl support - make sure that's enabled. Best bet is to try locally against your FMS box with the test database - once you've got that working then you can try the remote connection.
My project is to make a module enrollment system for our university. So I contacted the IT people in my university for details to authenticate the students into the system. We are developing the system using the existing university login. They gave me some LDAP information, I don't know the usage of that.
I'm using PHP,Mysql on an Apacha server.
How can I authenticate a user logging into my system, given his userid and password with the LDAP information.
Given below is the LDAP information(i have changed the domain name etc.)
LDAP information for blueroom.ac.uk domain
LDAP Host : ad.blueroom.ac.uk
LDAP port no: 389
BASE DN : ou=bluebird, dc=bluebird, dc=ac, dc=my
LDAP account to bind : cn = kikdap, ou=servacc, dc=bluebird,dc=ac,dc=uk
LDAP account password : ********
Attribute : sAMAccountName
The general procedure would be (relevant ext/ldap php commands in brackets):
connect to LDAP server using the "LDAP Host" and "LDAP port no" (ldap_connect()) and set the correct connection options (ldap_set_option()), especially LDAP_OPT_PROTOCOL_VERSION and LDAP_OPT_REFERRALS
bind to LDAP server using the "LDAP account to bind" and "LDAP account password" (ldap_bind()) - if you're authenticating against an Active Directory server you can directly use the username and password from the login page and skip all the following steps.
search the tree for a matching user entry/object by specifing the "BASE DN" and the appropriate LDAP filter - most likely something like (&(objectClass=user)(sAMAccountName=%s)) where %s should be replaced by the username to be authenticated (ldap_search())
check if the number of returned entries is 1 (if <> 1 then something has gone wrong, e.g. no user found or multiple users found)
retrive the distinguished name (DN) of this single entry (ldap_get_dn())
use the DN found in the last step to try to bind to the LDAP server with the password given at the authentication page (ldap_bind())
if the bind succeeds then everything is OK, if not, most likely the password is wrong
It's really not as hard as it sounds at first. Generally I'd propose to use some sort of standard library for authenticating against a LDAP server such as the Net_LDAP2 PEAR package or Zend_Ldap out of the Zend Framework. I have no experience with actually using Net_LDAP2 (although I know the code quite well) but Zend_Ldap works very well against Active Directory servers or ADAMS servers (which is obviously what you're working with).
This will do the trick using Zend_Ldap:
$options = array(
'host' => 'ad.blueroom.ac.uk',
'useStartTls' => true,
'accountDomainName' => 'blueroom.ac.uk',
'accountCanonicalForm' => 4,
'baseDn' => 'ou=bluebird,dc=bluebird,dc=ac,dc=my',
);
$ldap = new Zend_Ldap($options);
try {
$ldap->bind('user', 'password');
} catch (Zend_Ldap_Exception $e) {
// something failed - inspect $e
}
// bind successful
$acctname = $ldap->getCanonicalAccountName('user', Zend_Ldap::ACCTNAME_FORM_DN);
You might try http://code.activestate.com/recipes/101525/ while referring to http://us3.php.net/ldap and other results from a Google search for [php ldap authentication].
#Stephen provided good points. Here is my plain PHP code to authenticate using AD:
first you need to know this parameters: server host, user domain (you need also base dn if you want query AD).
use the following code:
$ldap = ldap_connect($host); // e.g. 165.5.54.6 or an URL
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3); // Recommended for AD
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
$bind = ldap_bind($ldap, $username.'#'.$userDomain, $passwrod);
if($bind){
// successful authentication.
}
you could use http://pear.php.net/package/Net_LDAP2/docs
it's nice and works.
Example of connection taken by the doc:
// Inclusion of the Net_LDAP2 package:
require_once 'Net/LDAP.php';
// The configuration array:
$config = array (
'binddn' => 'cn=admin,ou=users,dc=example,dc=org',
'bindpw' => 'password',
'basedn' => 'dc=example,dc=org',
'host' => 'ldap.example.org'
);
// Connecting using the configuration:
$ldap = Net_LDAP2::connect($config);
// Testing for connection error
if (PEAR::isError($ldap)) {
die('Could not connect to LDAP-server: '.$ldap->getMessage());
}