简体   繁体   中英

Php connection to database: is it secure?

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.php file under document root. The index.php bootstraps everything (ie 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.

Typically, this should be secure regarding your config data, if the hacker only has the URL to the file and if your webserver is configured properly so that the raw source code is not revealed.

You can increase security if you place such a config file outside the web root directory.

  1. Do not use mysql_* functions.
  2. Put the file in some other place that under the directory for the document root for the web server.
  3. Configure the web server to only allow connections from a list of IP addresses.
  4. Consider using a secure connection (SSL) always and configure the database to only use SSL.

Nothing will happen if anyone accesses this page.

Though mysql_* on itself is insecure.

It's safe. You can also store the file outside DocumentRoot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM