I'm refactoring PHP code to move from mysql_* and mysqli_* functions to PDO, and would like to accomplish this as efficiently as possible.
I use a file I call 'core.common.php'. I initializes the PDO database access object, has $_SESSION management features, and other features such as generic message and error notification functions (in the form of s.) I use the MsgBox() and ErrBox() functions extensively while developing and debugging. This file gets included at the top of every PHP-generated web page.
I have managed, at least through some testing, to successfully pass the PDO object (by injecting the PDO object in the __construct method) to classes that require database access.
It seems to me that this approach, while it still works so far, would only apply to each visitor of the site... Each visitor can use the same PDO connector throughout all pages they visit on the site.
My real questions are...
What happens when there are many visitors ?? Does each get their own PDO instance ? Would this mean that there would be many instances of database connections ?
The reason I'm asking is the host I currently use has "limited my resource usage" due to... according to them... "excessive resource usage". It is a "shared server". They suggest upgrading to a VPS (Virtual Private Server), and, of course at additional cost.
Is the host scamming me for more $$ ??
What, in the eyes of the Pros here, would be my best approach to this issue ?
And... Absolutely for all... Be critical and specific.
Any ideas are greatly welcomed !
What happens when there are many visitors ??
Exactly the same thing that happened with mysql and mysqli functions.
Does each get their own PDO instance ?
Yes. In a way.
Would this mean that there would be many instances of database connections ?
Yes. Just like it was with mysql functions.
the host I currently use has "limited my resource usage" due to... according to them... "excessive resource usage".
Make sure there is only one connection per script instance. According to your description it is already so, but just to be sure. That could be only issue with PDO. Also turn off persistent connection if used.
Regarding other aspects of this excessive usage, you better start a separate question, to ask recommendations on how to profile your code to get to the bottleneck.
Related
I would like to know if it's correct to re-use a PDO db connection multiple times ?
For example, I set it up in my controller then pass it as a parameter in a constructor of a class, is it correct to call the same connection (by using a function like get_Database) thoughout all my functions in the class and even pass it as a parameter in another class construct to continue working with the same connection ?
Or should I reopen a connection at some point ?
I was able to get it working by simply passing it around, however I am not quite sure if this would be performing well when going live.
Yes, you should reuse the connection.
Or should I reopen a connection at some point ?
The only reason to open a new connection is if connecting to another database. Otherwise, throughout a single script only one connection should be used.
To achieve this it is important to try and avoid using a static singleton throughout your application, rather learn about dependency injection to design your code to share the same PDO instance to every function or class that needs it.
however I am not quite sure if this would be performing well when going live.
As commented, if you reopen a connection often, it will be a lot slower.
There are many dependency injector's out there, and it is almost certainly a matter of opinion, but I like Auryn. Learning about it should help you design code where it is easier to share a single PDO instance, amongst others.
Yes, this is OK and it is better than connecting to the database many times.
The documentation even suggests to use the opened connection between calls to your php script / application:
Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.
Ok , so many people are asking this question, and there are many approaches on how to make the connection to DB secure,
Now I did some googling , many suggest, putting the connection to DB code in a file outside the html_public , and to call it from there when I need to make a connection.
to be honest, am happy with what I have, though I'm not sure how secure it is,
this is how I connect to the DB:
first, I make sure all inputs are fully escaped and validated...
after , in the same page , i make the connection, for example:
mysql_connect("localhost","Admin","Password") or
die ("DB Connection Error");
mysql_select_db("Users") or die ("DB Error");
and the rest of the code after, I close the mysql connection.
Now , It just don't feel right that the DB user info are written in the page, but how can someone (a "hacker") , get this info?
I mean , all inputs are fully escaped and validated, the users I use have very limited previleges, like select and update... only.
Is this secure?? and if not, can u please suggest a more secure way?
Thank you very much for ur help in advance :)
shady
The reason you should consider putting this file outside the web root is that some hosting providers have temporarily stopped interpreting PHP from time to time (due to configuration faults, often after an update on their part). The code will then get sent in clear text and the password will be out in the wild.
Consider this directory structure, where public_html is the web root:
/include1.php
/public_html/index.php
/public_html/includes/include0.php
Now consider this index.php:
<?php
include('includes/include0.php');
do_db_work_and_serve_page_to_visitor();
?>
If the web server starts serving this file in the open, it won't take long before someone tries to download include0.php. Nobody will be able to download include1.php, however, because it's outside the web root and therefore never handled by the web server.
I've personally not heard of a hosting provider not interpreting PHP, leading to your php source code going public. I just did a quick test on this on a RHEL5-Based server without php installed, and just got back a blank page when trying to access a php document.
mysql_* functions have become deprecated with the latest releases of php, and are now moving towards mysqli, as an overall more efficient and secure solution; I'd recommend taking a look into that; http://php.net/manual/en/book.mysqli.php - there's no deprecation errors or anything of the sort yet in PHP5.4 for using plain mysql_ functions, but if you're looking to keep on top of things, take a look into mysqli.
As for a quick answer to your above question, to be honest, I'd see that method as reasonably secure. Just make sure you've got escape chars etc set up, and I don't think you'll run into any issues.
Edit: Some people have posted that in very rare cases, some providers can leak your php source code in this manner. If this is the case, my first advice would be to switch provider.. but using an include_once to load your db info from another php file/lib would be a quick workaround for this. But again, if your provider's setup does allow for leaks such as these, I would be more concerned about their security than yours.
You can have php grab your DB password from a text file stored outside of the public webspace (using fopen), but I personally don't see any real reason for doing this.
Best of luck!
Eoghan
The best pratice is to use PHP PDO instead of the old mysql API.
Take a look: http://php.net/manual/en/ref.pdo-mysql.connection.php
Also, here's an interesting article: http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
I am building some new additions to an existing WebApp. The old code was written using mysql functions. Changing the entire application to use PDO would be a VERY man-hour-intense thing to do. However, for all new code, I'd like to begin using PDO.
Are there any concerns I need to be aware of for using PDO within an existing application that does NOT use PDO to interface with the database? It's no problem to connect to the DB using both/either of these options at the same time when a page is loaded, correct?
While I'm at it - I am interested to know how big the need is to close a PDO connection after a page loads - or is it fine to leave the connection open?
Thanks all.
There's no need to close any type of database connection when a page finishes loading - PHP always does this for you (unless you make the mistake of enabling persistent connections).
However, if you use PDO AND mysql_ in the same page, connecting to the same database, it will consume twice as many connections (while the page is executing) on the server. This may or may not be a problem.
Personally I would recommend that you remain consistent within the application if you don't want to refactor it to use PDO throughout.
Currently, I am dealing with a social network startup. We use php & mysql for back-end development. I have a datamanager.php that have functions which handles the sql connections and queries. I have several functions like signup, login, get_profile, etc.
I have 2 choices for handling mysql connection
1) create a globally reachable $connection variable with mysqli_connect(); and don't close the connections until I finish all the database operations.
2) create a function namely db_connect() that returns the connection variable in each database functions. Also, in each database function like login, signup, I close the connection with mysqli_close(); and get another connection variable with db_connect();
So, which choice is better for handling mysql connections and why ?
It's better to keep the MySQL connection open as of performance. Better use a class to handle all mysql connections and somehow pass the instance of the class (i.e. the object itself) to all other functions/classes which need it. Within the class you could establish the connection ONCE and than keep it!
Firstly, on the assumption that you are building something that needs to have a long shelf life, and scale to lots of users, with a roadmap for new features, I'd encourage you to use an off-the-shelf PHP framework; Zend or Symfony seem to be the front runners. These frameworks provide a lot of the plumbing for you, so you won't have to worry about database connections.
However, specifically answering your question, I'd encourage you to use mysql_pconnect - it frees you up from worrying about opening and closing connections. You do need to read the manual, it's not totally straightforward...
I'm quite new on php and am trying to learn it.
My question is rather simple but I've been a bit lost while googling for it.
I just want to create an object to manage the database connection. I already did the object and now the problem I'm facing is:
How do i keep it instanced to a session? (So that i don't need to open/close the connection to the database on every page load) And how do I call it afterward?
Are there any way to declare a destroyer, so that when the instance is dying, the connection to the database gets closed?
If you define a __destruct() method on your object, it'll get called when the object is about to be destroyed. You can use this to close your database connection.
You can also use __sleep() and __wakeup() for serializing your objects. They'll get called automatically upon serialization and unserialization. You could use these methods to connect and disconnect as required.
I hate to answer by refuting the question but I think you are going about resolving the problem in the wrong way here.
Rather than worrying about the connection being opened/closed I would suggest using caching, indexing, etc. to solve performance problems when they arise rather than being concerned about the resources involved in establishing a connection.
If you are really concerned about performance why not cache the affected pages and avoid using the database connection at all?
I think you could get the desired effect with this function (don't use this myself, assuming mysql) but be sure to read the comments:
http://www.php.net/mysql-pconnect
I don't think you want to start using sleep/wakeup techniques as to get this working as I understand it would involve creating a whole bunch of separate threads each with its own database connection which will just sap your resources and produce the opposite of the intended effect.