Connecting to a mysql database without keeping details in the script - php

I am attempting to create a separate login file for database connections as I am not too fond of having all the access details on each page that requires database access.
I have created a separate file on my server that contains the variables required for a successful login and then use the;
include_once('path_to_file/filename.php');
to get the variables and then use;
$dbconnection = mysqli_connect("$hostname","$username","$password","$database") or die ("Could not connect to the server");
but the connection fails every time. I tried including the connection script in the file I am attempting to include but then I get this message:
Can't connect to local MySQL server through socket '/tmp/mysqld.sock' (2)
I'm not really sure how to fix this, but every page in my server more or less access the database and I think it has to be a security risk having login details replicated everywhere!
Anyone have any suggestions or alternatives?
databaseloging format is:
<?php
# parameters for connection to MySQL database
$hostname="hostname";
$database="databasename";
$username="username";
$password="password";
?>
P.S. I have also tried require and got the same result.

Also when using multiple MySQL connections in PHP, you have to supply a fourth argument telling PHP to actually create new connections like this (this is very important, if you are using two connections to the same host):
$db1 = mysql_connect($host1, $user1, $passwd1, true);
$db2 = mysql_connect($host2, $user2, $passwd2, true);
If the fourth argument is not used, and the parameters are the same, then PHP will return the same link and no new connection will be made.
After this you should use "mysql_query" with an extra parameter than defines which connection to use:
$res1 = mysql_query($sql1, $db1) or die(mysql_error($res1));
$res2 = mysql_query($sql2, $db2) or die(mysql_error($res2));
http://www.php.net/manual/en/function.mysql-connect.php

Related

PHP OCI: Connection string (convert from JDBC)

I have below obfuscated connection string in SQL developer which works:
jdbc:oracle:thin:#//xyz-scan.example.com:1521/mydb.example.com
How can I use this in php oci_connect?
$db = 'xyz-scan.example.com:1521/mydb.example.com';
$con = oci_connect('scott', 'tiger', $db, 'AL32UTF8');
Lead to error:
ORA-12545: Connect failed because target host or object does not exist
I can ping the server successfully.
I also tried
$db = '(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)
(HOST = xyz-scan.example.com)(PORT=1521))
(CONNECT_DATA=(SERVER=DEDICATED)
(SID=mydb.example.com)';
And instead of SID with service_name. Nothing works.
Above gives this error:
ORA-12154: TNS:could not resolve the connect identifier specified
How do I convert this connection string to work with php oci? (is there a unique way? For a different db I have one with #ldap://... how would I convert that?
The solution to first issue with scan address is simple:
$db = '(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)
(HOST = xyz-scan.example.com)(PORT=1521))
(CONNECT_DATA=(SERVER=DEDICATED)
(SID=<sid>)';
The second one with ldap is not so simple. As far as I understood oracle has it's own ldap thingy and in it you store the databases TNS entries. This means you query it like you query any ldap system:
<?php
$ds=ldap_connect("oid.mydomain.com", myport); // Connect to oracle ldap
$r=ldap_bind($ds); // Bind to ldap
$sr = ldap_search($ds, "cn=OracleContext,dc=xyz,dc=abc,dc=com", "cn=dbname"); // Run query xyz.abc.com
$info = ldap_get_entries($ds, $sr); // Get entries
ldap_close($ds);
$dbconnectstring = $info[0]["orclnetdescstring"][0]; // Extract db connect string from ldap search result array
$con = oci_connect('scott', 'tiger', $dbconnectstring);
?>
This script will get full TNS connection string which you can then use with oci_connect.

Is the correct way to connect my website to my server?

I'm a total beginner when it comes to PHP, I have a fair grasp of the syntax but I'm not sure about the safest way to utilise it to connect to my server. I apologise that this is a sort of generic question rather than a code problem, since my code technically works.
I have a .php site doc with a basic comment submission form. The only way I can think of to connect to the server is to allow a "dummy" user with select only privelege to call a stored function to accept the comment.
If my dummy account is called siteuser then am I going round this the right way? This is the section of the PHP that I'm using to connect. I believe this code is only visible server side so nobody can ever see it and use the password or username to connect some other way? Or is there a sort of default string I can use in my php without creating the dummy user, seeing as the php and server is all hosted via the same provider?
$sqlserv = "localhost";
$sqlname = "siteuser";
$sqlpass = "mypassword";
$sqldbdb = "comments_table";
$conn = new mysqli($sqlserv, $sqlname, $sqlpass, $sqldbdb);
What i do is this to connect to my DB
db.php:
<?php
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file('/somepath/config.ini');
//Mysqli Connection
$conn = new mysqli($config['host'], $config['user'], $config['pass'], $config['dbname']);
if($conn->connect_errno > 0){
die('Unable to connect to database [' . $conn->connect_error . ']');
//Set encoding
mysqli_set_charset($conn, "utf8") or die;
}
?>
and in config.ini:
[database]
user = johndoe
pass = someweirdpassword
dbname = the_name
host = localhost
both files have 700 permissions, so only user (and no one else can access it)
also the config.ini file is placed somewhere outside the public_html directory, i'm not totally sure if that helps or not but i do it that way.

PHP - Best way to connect to database when there are multiple connections

I have just recently acquired the service side of a medium size project. The former developer has all of his functions as separate php scripts instead of classes (func1.php, func2.php, etc)... All these 'functions' make a reference to mysqli_connect via referencing the actual
'databaseonnection.php' file. This is creating a new connection every time any of the scripts run (every time I have to call a function) and I don't want to do that. I was thinking about having a persistent connection, but I'm worried about it getting out of hands as the project is growing more and more every day. So, has anyone ever encountered a similar situation? What is the best way to handle my connection to the database? Any suggestions would be greatly appreciated.
From the docs for mysql_connect. If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.
EDIT: I'm sorry I thought you wanted connectivity help. There is no way except to move all those "functions" into one file where the connection is for them only.
I create a con.php file where my PDO connection is established then include that file anywhere you wish to use a connection Here is the base for a PDO connection:
$PDO = new PDO("mysql:host=localhost;dbname=dbname", "user_name", "password");
Here is my notes on using the PDO object to make prepared queries. There is more than you need below but good luck.
Within your PHP file that needs a connection:
1: include('con.php');
2: $datas = $PDO->prepare(SELECT * FROM table WHERE title LIKE :searchquery);
// prepare method creates and returns a PDOstatment object ( print_r($datas); ) which contains an execute() method
// PDOstatment object has its own methods ie. rowCount()
// $datas->bindValue(':search', '% . $search . %', )
// Optional - Manually bind value. see http://php.net/manual/en/pdostatement.bindparam.php
3: $datas->execute( array(':searchquery' => $searchquery . '%'));
// pass in values that need to be bound AND EXECUTE.
// There are 17 ways to "fetch" data with the PDO object.
4: $datas-fetchALL(PDO::FETCH_OBJ);
close a pdo connection by the handle:
$PDO = null;
I think you'll be much better off using PDO as opposed to the old MYSQL functions e.g. mysql_connect. It's much more robust an interface.
Below is the basic code to do this:
$db_handle = new PDO("mysql:host=".$db_host.";dbname=".$db_name.";port=".$db_port."", $db_username, $db_password, $connect_options);
where $db_handle is the PDO object representing the database connection, $db_host is your hostname [usually localhost], $db_name is the name of your database, $db_port is the database port number [usually 3306], $db_username and $db_password are your database user access credentials, and $connect_options are optional driver-specific connection options.
To enable persistent connections you need to set the driver-specific connection option for it before opening the connection: $connect_options = array(PDO::ATTR_PERSISTENT => true); then execute the earlier database connection code.
You can get more information on this from the PHP Docs here: http://www.php.net/manual/en/pdo.construct.php and http://php.net/manual/en/pdo.connections.php.
Regarding creating persistent connections, I would suggest that you close every database connection you open at the end of your script (after all your database operations of course) by nullifying your database handle: $db_handle = NULL;. You should do this whether you opened a persistent connection or not. It sounds counter-intuitive, but I believe you should free up any database resources when your script is done.
The performance disadvantages of doing this [from my experience] are neglible for most applications. This is obviously an arguable assertion and you may also find the following link helpful in further clarifying your strategy in this regard:
Persistent DB Connections - Yea or Nay?
Happy coding!
if you have very complex project and need big budget to re-design, and prefer very simple alteration then
1) stay in mysqli_connect
2) move the database connection to header of your script.
3) remove the function databse close() on that functions.
4) remove the connection link variables, it wont needed for single database.
5) close the database on end of footer.
By this way, database connection establish when starting your script and after all queries, it will be closed on footer. your server can handle the connections without closing/re-open by using keepalive method. basically default keepalive value is 30 to 90 seconds.

Remote connection to MySQL works via command line, but fails when using php's mysql_connect from a web browser

I am trying to connect to a MySQL server using PHP's 'mysql_connect()' function, but the connection fails. This is my code:
$con = mysql_connect("example.net", "myusername","") or die("Could not connect: ".mysql_error());
I placed this code inside a PHP script, which I try to open using a web browser (the script is stored on a remote host which has PHP enabled) but it doesn't work. It doesn't return the die error either. Echoing something before the $con successfully outputs in the browser, whereas nothing outputs after that line. If I type:
mysql -h example.net -u myusername
from a remote machine, I could connect to the DB without any problem and do queries and other modifications.
Update :
I also tried this after some suggestion, but no improvement:
<?php
$usern = "myusername";
$dbh = new PDO('mysql:host=servername.net;dbname=test', $usern, "");
echo $usern;
?>
What operating system is the remote host running PHP using? Perhaps MySQL isn't enabled in php.ini. Also, please don't use mysql_* functions for new code. They are no longer maintained and the community has begun the deprecation process (see the red box). Instead, you should learn about prepared statements and use either PDO or MySQLi. If you can't decide which, this article will help you. If you care to learn, this is a good PDO tutorial.
Have you tried using PDO or the MySQLi interface? If you're trying to learn PHP, you should not be using the mysql_* functions regardless. See if you can access the database by using a line similar to this:
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
If you need more detailed documentation, this code comes directly from the documentation itself.
EDIT: Also, try using PDO's error checking functionality. This example creates a database connection using PDO and tries to perform a simple query. It doesn't use prepared statements or any of those features, so it's not production-ready code (i.e. *don't just throw this into your code without understanding how to improve it) and you'll need to edit it to include a SELECT query that's relevant to your database, but it should at least tell PDO to provide more information about the errors it encounters.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "admin";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM booksa";
$q = $conn->query($sql) or die("ERROR: " . implode(":", $conn->errorInfo()));
$r = $q->fetch(PDO::FETCH_ASSOC);
print_r($r);
?>
Is the php file located on the same server as the mysql database, if so you might have to use 'localhost' as the first argument for mysql_connect() instead the external address.

How do I detect database name using MySQL PDO

I am rather new to the PDO library, so I apologize for my inexperience. I am writing a class that uses the PDO library to build and execute queries and return the results, no matter what they are.
Within the class, I detect whether there is an open connection to a database, and if it is the same as the one being configured, it uses this one instead. This is really easy to do using the MsSQL library as the PDO::getAttribute() function returns 'CurrentDatabase' and 'SQLServerName', so I can just apply a condition like so:
if(!empty($this->PDO)){
// Get the current connection information
$current_connection = $this->PDO->getAttribute(PDO::ATTR_SERVER_INFO);
// Return if the connection is the same
if($this->connection_parameters['hostname']==$current_connection['SQLServerName']&&$this->connection_parameters['database']==$current_connection['CurrentDatabase']){
return;
}
}
However, when it comes to MySQL, the data returned from PDO::getAttribute is completely different and I cannot seem to get the database name from the current connection.
Does any body know a function or method to get the currently connected database of a MySQL connection using the PDO library in PHP?
I order to connect to both MySQL and MsSQL, you must have 2 connections. However, changing the database on a live connection is very simple.
The following simply checks if a PDO instance already exists and whether or not it is using the required database. If so then it continues with this connection, if not it changes the database.
// Test if the PDO object already exists
if(!empty($this->PDO)){
// If connection is the same then select the database
if($this->connection_engine==$this->PDO->getAttribute(PDO::ATTR_DRIVER_NAME)){
// Get the current database in use
$database = $this->PDO->query("SELECT {$this->select_db_function}");
$database = $database->fetchAll(PDO::FETCH_NUM);
$database = $database[0][0];
// If the current database matches the new database then return
if($database==$this->connection_parameters['database']){
return;
}
}
}
I see no point in looking for the opened connection and - especially - in checking for the current database.
Why can't you just open the connection, select the database for it and then use this connection all the time throughout your class - just like everyone does?
See comments on the MySQL manual page for 'USE database'

Categories