I have a project we are about to wrap up, but just got a request from the DBA to make all our connections SSL. So I switched the driver to mysqli in the object that turns out ADODB instances, but I don't see any native method to create secure connections.
To make things more difficult, there is a different set of certs and keys per connection type (read and write).
Anyone have any ideas?
The trick is to use a DSN in the
NewADOConnection() call (rather than
authenticating with a Connect() call)
and to use the mysqli driver. The DSN
syntax allows you to supply client
flags, and there's a mysqli flag for
using SSL certificates.
$dsn = 'mysqli://ssluser:sslpass#dbhost/test?clientflags=2048';
$dbh = NewADOConnection($dsn);
$sql = "show status like 'ssl_cipher'";
$res =& $dbh->Execute($sql);
print_r( $res->fields );
$res->Close();
$dbh->Close();
The answer to this question is found at:
http://mbrisby.blogspot.com/2008/06/adodb-php-mysql-ssl.html
Here is the reference to MySQL Client Flags:
http://forge.mysql.com/wiki/MySQL_Internals_ClientServer_Protocol
I prefer the one with the Connect method, and clientFlags property.
$dbc = NewADOConnection('mysqli');
$dbc->clientFlags = CLIENT_SSL;
$this->dbc->Connect('dbhost', 'ssluser', 'sslpass', 'test');
Either of them would work.
Related
I am used to mysql database access using the procedural mysql method. I am a beginner - intermediate programmer.
I am trying to learn the PDO api, however all resources which discuss using PDO show the connection string, username and password.
e.g.
<?php
try {
$db_conn = new PDO('mysql:host=localhost;dbname=databaseName','username', 'password');
}
catch (PDOException $e) {
echo 'Could not connect to database';
}
$sql = 'SELECT * FROM Products';
$stmt = $db_conn->prepare($sql);
...
...
...
?>
What I want, and think would be better programming is to put my PDO connection into a new file. then where I want to run an SQL query, I require_once('PDO.php') or similar.
The problem I have with this is as follows:
How do I close the connection? Simply $db_conn = null; ??
Should I close the connection after each query is run, then re-open the connection?
Should I close the connection or is it automatically destroyed when the user closes the browser?
I am working from a book called PHP Master: Writing Cutting Edge Code. http://www.sitepoint.com/books/phppro1/ and this has completely omitted any reference to closing the connection / destroying the object after it has been used.
Furthermore, I have looked at online tutorials, and they all connect to the database using PDO inline as opposed to having a separate database connector. This I am not happy with for many reasons:
I have to type username & password to connect every time.
If I get a developer to take a look at code / write some code, they will all have access to the database.
If I change the DB username & Password, then each file which connects to the database will need to be updated.
Could anybody recommend a better resource? Could anybody advise on what is the best practice way to do this?
Many thanks
Your question about how to store the database name, username and password have nothing to do with the capabilities of PDO. This is an implementation choice. The way you use to work with procedural functions can also be applied to PDO, the difference is that with PDO you work with objects instead.
So for simplicity, store the PDO creation of an object, either in a function or class, in which you can create the PDO instance anytime, e.g.
function createPDO($cfg) {
try {
return new PDO("mysql:host=".$cfg['host'].",port:".($cfg['port']).";dbname=".($cfg['name']).";",$cfg['username'], $cfg['password']);
} catch(PDOException $e) {
// handle exceptions accordingly
}
}
You can centralise these in whatever PHP file you like to include, just like you were used with the procedural functions.
You have two choices, either put all the relevant database information inside the createPDO, or use something like a config ($cfg) variable to store all this information.
$config = array();
$config['db'] = array(
'host' => 'localhost',
'name' => 'databse',
'username' => 'userx',
'password' => 'passy'
/* .. etc */
)
Using the createPDO function would be as followed
$db_conn = createPDO($config['db']);
For connections closing, each connection made to the database automatically disconnects after PHP exits its execution. You can however, close the connection if you wish, by setting the variable of the PDO object you assigned it to, in this example (and in yours) $db_conn to null
$db_conn = null; // connection closed.
The PDO has a manual http://php.net/manual/en/book.pdo.php here, which is a good start getting to know PDO a bit better.
You do not close the connection after a query, you simply leave it open for the next query. When PHP exists and your page is shown, the connection will be closed automatic.
It is a good idea to put the db stuff in a separate file and include that.
Even better, put all your db stuff in a class in use that.
Have a look at the pdo php page. Although not the best examples, they should get you started.
I am thinking to connect to 2 database in my project in php.
one is an existing database from our ticketing system that uses MS ACESS and the other one is the one im using now its MYSQL.
The use of the MS access is just to retrieve data from it and the MYSQL will be used to both retrieve and store data.
Is it possible to connect to both database at the same time??
Short answer: Yes.
Long answer:
You should ensure that your code always uses connection identifiers to avoid confusion and have clean, readable code. (Especially when you connect to both databases using an abstraction layer like ODBC or PDO)
Please look into the PHP Manual on PDO and connection management
Example:
$link_mysql = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$link_msaccess = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\\test.mdb");
// query MySQL DB
foreach($link_mysql->query('SELECT * FROM test') as $row) {
print_r($row);
}
// query MS Access DB
foreach($link_msaccess->query('SELECT * FROM omg_its_access') as $row) {
print_r($row);
}
Example without PDO:
$link_mysql = mysql_connect("localhost", $user, $pass);
mysql_select_db("test", $link_mysql);
$link_msaccess = odbc_connect("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\\test.mdb");
// you may omit the link identifier for MySQL, but i suggest to use it explicitly
$res1 = mysql_query('SELECT * FROM test', $link_mysql);
while ($row = mysql_fetch_row($res1)) {
print_r($row);
}
// for ODBC the link identifier is mandatory
$res2 = odbc_exec($link_msaccess, 'SELECT * FROM omg_its_access');
while ($row = odbc_fetch_row($res2)) {
print_r($row);
}
As you see above, the code for the two database drivers differs in its syntax - that is why i suggest to use PDO.
PDO will avoid a lot of hassle and will make switching to another database driver much easier if you decide to do so later. It abstracts all database drivers and gives you a simple interface to handle them all with the same syntax.
if you're using PDO, for example, thats possible. just create one pdo-object for each connection - just use the mysql-driver for mysql and an odbc-connection for access.
As I know PDO support has been added to codeigniter recently but I can't find any documentation or tutorial about how to actually use it. Can anyone tell how can I use it?
You can edit /application/config/database.php and to enable the PDO driver:
$db['default']['hostname'] = 'pgsql:localhost';
// or mysql:localhost
// or sqlite::memory:
$db['default']['dbdriver'] = 'pdo';
If you want to directly get you hand on the active DB connection. This might work, but I am not CI developer .. so no guarantees. I tried to understand that brain rotting code, but i suspect, that i failed. I'm not good at PHP4 + eval():
$CI = get_instance();
var_dump($CI->db->conn_id);
// should show that conn_id is instance of PDO
Well, since CodeIgniter is merely a PHP framework, nothing prevents you from using it natively, as in $pdo = new PDO(...);.
However, when they say PDO is now supported, I think they mean their normal Database class now uses PDO (rather than MySQLi or the such).
I'm using PDO to access two SQLite 3 databases in PHP. I want to switch the database files during a query by renaming them but I can't do that while the files are open as it gives an error that the file is being used by another process. I've tried turning off persistent connections and setting the handles to null but neither work.
Is there really no way to close a PDO handle and release the lock on the database file?
I believe unset($var) does that, I use it on my pdo sqlite project and it works like I want it to :)
Set all references to the handle to null (or to anything except the PDO object, really) and the runtime will destruct the object, which will close the connection.
$db = new PDO('...');
// Do some stuff
$db = null;
// Assuming this was the last reference to that PDO
// object, the runtime will destroy the object and
// its connection.
The SQLite3 Class has an option like this.
$db = new SQLite3('mysqlitedb.db', SQLITE3_OPEN_READONLY);
In PDO you would simply open with:
$db = new PDO('sqlite:mysqlitedb.db');
My question is however, is there a way to open a database with PDO, in READONLY mode?
This will become possible with the release of PHP 7.3 (estimated for release in late 2018).
The syntax is as follows:
$db = new PDO('sqlite:mysqlitedb.db', null, null, [PDO::SQLITE_ATTR_OPEN_FLAGS => PDO::SQLITE_OPEN_READONLY]);
Upstream commit
I don't think that's possible with pdo (yet?).
The pdo_sqlite driver of php 5.3 uses sqlite3_open() in pdo_sqlite_handle_factory() but you need sqlite3_open_v2() to pass the read only flag.
edit:
But a patch would be fairly easy. Take a look at pdo_mysql_handle_factory() in ext/pdo_mysql/mysql_driver.c and how it uses struct pdo_data_src_parser vars[] to parse the dns string.