I use the following php code to connect to mysql database.
$hostname = "hostname.com";
$database = "dbtest";
$username = "admin";
$password = "pass123";
$connect = mysql_pconnect($hostname, $username, $password) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database);
This code is placed in a connection file called connect.php which is included in all php scripts that require access to database.
If a hacker gets the url of connect.php (http://www.domainname.com/connect.php), is it possible to hack my database.
How can I ensure that the php connection code does not help the hacker? Or Which is the best secure way of connecting to the database?
You should never ever have PHP files with code inside the document root of your website. The only thing in the document root should be a bootstrap file and route all requests through this. If you would have that file inside the document root of your site and for some reason the webserver doesn’t parse the file it will be displayed as is.
And 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, this article will help to choose. If you care to learn, here is a good PDO tutorial.And always use an ecrypted connection (SSL).
See this for routing examples and dispatching patterns. Basically what should happen is: all request are handled by the
index.phpfile under document root. Theindex.phpbootstraps everything (i.e. calls (includes)) another file outside of the document root. This file will check the URL of the request and finds out what file belongs to current URL and executes it.